I wanted to read the content of a file using the read() function. I tried the following:
#define BUFFER_LENGTH (1024)
char buffer[BUFFER_LENGTH];
// The first version of the question had a typo:
// void read_file(const char filename)
// This would produce a compiler warning.
void read_file(const char *filename)
{
ssize_t read_bytes = 0;
// The first version had the mode in hex instead of octal.
//
// int fd_in = open(filename, O_RDONLY, 0x00644);
//
// This does not cause problems here but it is wrong.
// The mode is now octal (even if it is not needed).
int fd_in = open(filename, O_RDONLY, 0644);
if (fd_in == -1)
{
return;
}
do
{
read_bytes = read(fd_in, buffer, (size_t) BUFFER_LENGTH);
printf("Read %d bytes
", read_bytes);
// End of file or error.
if (read_bytes <= 0)
{
break;
}
} while (1);
close(fd_in);
}
I am using 'gcc (GCC) 3.4.2 (mingw-special)' on a Windows 7 system.
The strange behaviour I get is that not all the content is read. For example, I have
a file
05.01.2012 12:28 15.838 hello.exe
and when I try to read it I get:
Read 216 bytes
Read 0 bytes
As far as I know read() should keep reading until it reaches the end of the file. While does
it report an end of file (0) the second time it is called?
Maybe I am missing something obvious but I cannot see it. I have read this document and this document over and over again and I cannot find what I am doing wrong. Does anyone have any clue?
EDIT
Thanks for the hint! It is a typo in the question (I have corrected it). It is correct in the source
code.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…