Tariq Kamal
Tariq Kamal

Reputation: 496

read() system call does not return EOF

I am trying to read all data from a file using open() system call. But I am having difficulties figuring out the end of file. The C EOF flag doesn't work. My program goes into an infinite loop. Here is the code. The file has less than 100 characters in it.

int main()
{
 char buf[100] = {""};
 i = 0;
 int fd = open ("file1.txt", O_RDONLY);
 int bytesread = read (fd, &buf[i], 1);
 char c = buf[i];
 while (c != EOF) {
    i++;
    int bytesread = read (fd, &buf[i], 1);
    c = buf[i];
 }
}

Upvotes: 1

Views: 4079

Answers (2)

P.P
P.P

Reputation: 121427

read(2) doesn't return EOF. Its return values are: 0 on reaching "end-of-file", -1 on error, positive value when as many bytes are read. Besides you are checking the data for EOF. Your loop condition is wrong.

Typically, you'd also check if read(2) was interrupted and if so, retry.

size_t i = 0;
errno = 0;
while (i < sizeof buf && read (fd, &buf[i], 1) >= 0 && errno != EINTR) {
    i++;
    errno = 0;  
 }

I am also not why you are reading only one byte at a time, which is not very efficient. You could always read chunks of data and check the return value to know the number of bytes read.

Note: Typically the macro EOF is also defined with value -1. So it could seem read(2) returns EOF but don't be confused.

Upvotes: 3

Mukesh Verma
Mukesh Verma

Reputation: 534

The buffer doesn't holds EOF, it just hold the data in the file read.What you can do is

while(bytesread > 0 ){
    i++;
    bytesread = read (fd, &buf[i], 1);
}

Upvotes: 2

Related Questions