Reputation: 61
I'm writing a C code that will read content of file and output it on the terminal. This is my code so far:
rdfd = open(address, O_RDONLY);
read(rdfd, reader, 1);
while(rdfd != 0){ //will end if EOF is reached
for(x=0; x<1; x++) printf("%c", reader[x]); //for printing at the terminal
read(rdfd,reader,1);
}
Now, for an example, I have an index.html
file with the ff content:
<html>
<body><h1>HELLO WORLD</h1></body>
</html>
The program will print something like this:
<html>
<body><h1>HELLO WORLD</h1></body>
</html>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> (...)
The >
will just go on infinitely. I don't know why. Was there something wrong with the while condition?
Upvotes: 1
Views: 54
Reputation: 976
rdfd is the File Descriptor of the file you are reading from. Testing it for zero (while(rdfd != 0)
actually doesn't do anything useful. If you want to test whether the file was opened correctly (you should) test if for < 0.
If you want to know when the end of the file is reached, check the return value from the read call, i.e:
int bytesRead = read(rdfd, reader, 1);
while (bytesRead > 0)
{ ...
bytesRead = read(rdfd,reader,1);
}
Upvotes: 1