我想使用read()函数来读取文件的内容。 我尝试了以下内容:
#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\n", read_bytes); // End of file or error. if (read_bytes <= 0) { break; } } while (1); close(fd_in); }
我在Windows 7系统上使用'gcc(GCC)3.4.2(mingw-special)'。
我得到的奇怪的行为是,并不是所有的内容都被读取。 例如,我有一个文件
05.01.2012 12:28 15.838 hello.exe
当我尝试阅读时,我得到:
Read 216 bytes Read 0 bytes
据我所知read()应该继续阅读,直到它到达文件的结尾。 而第二次被调用的时候是否会报告文件结尾(0)?
也许我错过了一些明显的东西,但是我看不见它。 我已经一遍又一遍的阅读这个文档和这个文档 ,我找不到我做错了什么。 有没有人有任何线索?
编辑
感谢提示! 这是一个错字(我纠正了它)。 在源代码中是正确的。
我怀疑字节217是EOF(26,0x1A) – 在Windows文件可以打开在“文本”或“二进制”模式。 在文本模式下,0x1A被解释为EOF。
你需要看看你的开放模式 – O_BINARY。 在PHP中,这就是为什么你必须打开模式“RB”(READ BINARY)而不是“R”(默认为READ TEXT的“R”)。
http://www.mingw.org/wiki/FAQ说这个标志是O_BINARY(接近页面底部),所以你需要
int fd_in = open(filename, O_RDONLY | O_BINARY, 0644);
void read_file(const char filename)
然后:
int fd_in = open(filename, O_RDONLY, 0x00644);
不要忽略编译器警告。 我很惊讶,这不只是崩溃。
你可能想尝试使用O_RDONLY | O_BINARY
O_RDONLY | O_BINARY
或O_RDONLY | O_NOTRANS
O_RDONLY | O_NOTRANS
在公开通话中。 通过不指定O_BINARY或O_NOTRANS,可以在文本模式下打开文件,读取将在第一次遇到EOF字符时停止。
我在我的机器上试过你的代码:
它在我的机器上的示例文件工作正常。 我读取的文件是C:\Windows\System32
cmd.exe
,并将read_file
函数的总字节数与磁盘上的实际文件大小进行了比较。
这表明了两件事之一: