How to EOF??
I have this code:
Unfortunately, it's printing out an endless number of blank lines at the end, forever.
int read1 = read(fd, &c, 1);
while ( c != EOF )
write(1, &c, 1);
read1 = read(fd, &c, 1);
I *think* it's because of this:
EOF = -1, and its size is 4 bytes
printf("EOF: %d, %d\n", EOF, sizeof(EOF));
So, since it's only reading 1 byte at a time, it never gets an EOF. (I *think*)
Am I doing something wrong? Is there a way to make this work?
The function read() will return the number of bytes it read - so instead of comparing c with EOF, you need to check the return value from read().
while ( read1 != 0 )
Originally Posted by matsp
Thanks again Mats!!!!
> EOF = -1, and its size is 4 bytes
Yes. Hence it won't fit in a char. Unless it's signed and you truncate.
see post #6 ;)[/edit]
Originally Posted by zacs7
It WILL print -1, even from a char. All signed types in C can hold the value -1.
signed char c = EOF;
printf("c = %d\n", c);
The reason "sizeof(EOF)" is 4 is that the default type is int, EOF itself is a macro that expands to -1, which then leads to sizeof(-1), and just like sizeof(0) or sizeof(42), it will give the same value as sizeof(int), becuase unless you specifically make it otherwise, numeric constants are integers.
The other misconception here is that EOF is somehow part of the file - it is not. The end-of-file is known by the filesystem because it knows how many bytes there are in the file - and when it reaches the end of that, it refuses to read any more.
In CPM, the end-of-file in text-files was marked with a CTRL-Z, non-text files were always a multiple of the block-size (128, 256 or 512 bytes, traditionally) [although a well-formed binary file would have information within the file to show the amount of actual content, of course]. But MS-DOS, Unix/Linux, Windows, MacOS all have exact sizes of files with no particular markers at the end [although Windows still supports CTRL-Z as a end-marker].
Yes I meant to say signed, don't know why I wrote unsigned.