c - reading a file that doesn't exist -


i have got small program prints contents of files using system call - read.

unsigned char buffer[8]; size_t offset=0; size_t bytes_read;  int i;  int fd = open(argv[1], o_rdonly);  do{     bytes_read = read(fd, buffer, sizeof(buffer));     printf("0x%06x : ", offset);      for(i=0; i<bytes_read; ++i)     {         printf("%c ", buffer[i]);     }     printf("\n");     offset = offset + bytes_read; }while(bytes_read == sizeof(buffer)); 

now while running give file name doesn't exist. prints kind of data mixed environment variables , segmentation fault @ end.

how possible? program printing?

thanks, john

read returning -1 because fd invalid, store in bytes_read of type size_t unsigned, loop prints (size_t)-1 chars, large number, larger size of buffer. so, you're printing big chunk of address space , getting segfault when reach end , access invalid address.

as others have mentioned (without answering actual question), should checking results of open error. e.g.,

int fd = open(argv[1], o_rdonly); if( fd < 0 ){     fprintf(stderr, "error opening %s: %s\n", argv[1], strerror(errno));     exit(1); } 

a caveat: if system call, or call routine might system call (e.g., printf) before calling strerror, must save errno , pass saved copy strerror.

another note program:

while(bytes_read == sizeof(buffer)) 

this not test, because read can return less amount ask for. loop should continue until read returns <= 0.


Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -