View Single Post
Old 05-26-2003, 07:34 AM   #2 (permalink)
joe_bruin
LOAD "*",8,1
 
Join Date: Feb 2003
Location: la.ca.us
Posts: 254
joe_bruin is on a distinguished road
here is a program that uses read(2) to read binary data. it has no problems with 0x1a or any other character, and is much faster than multiple getc's.

Code:
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

int main()
{
  int len, fd, i;
  unsigned char buf[1024];

  fd = open("in.txt", O_RDONLY);
  if(fd == -1)
  {
    perror("open");
    return 1;
  }

  len = read(fd, buf, sizeof(buf));
  if(len == -1)
  {
    perror("read");
    // should probably check errno here
    return 1;
  }
  if(len == 0)
  {
    printf("eof reached\n");
  }
  else
  {
    for(i = 0; i < len; i++)
    {
      printf("%02x ", buf[i]);
      if(i % 8 == 7) printf("\n");
    }
  }
  close(fd);

  return 0;
}
joe_bruin is offline   Reply With Quote