reading a file that doesn't exist

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • john eipe
    New Member
    • Feb 2011
    • 2

    reading a file that doesn't exist

    Hi,

    I have got a small program that prints the contents of files using the system call - read.

    Code:
    	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 I give a file name that doesn't exist.
    It prints some kind of data mixed with environment variables and a segmentation fault at the end.

    How is this possible? What is the program printing?
  • horace1
    Recognized Expert Top Contributor
    • Nov 2006
    • 1510

    #2
    you should check that the file opened OK
    Code:
       int fd = open(argv[1], O_RDONLY);
    otherwise when you attempt to read you get rubblish or segmentation faults, see

    Comment

    Working...