我想使用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);
}
Run Code Online (Sandbox Code Playgroud)
我在Windows 7系统上使用'gcc(GCC)3.4.2(mingw-special)'.
我得到的奇怪行为是并非所有内容都被阅读.例如,我有一个文件
05.01.2012 12:28 15.838 hello.exe
Run Code Online (Sandbox Code Playgroud)
当我尝试阅读它时,我得到:
Read 216 bytes
Read 0 bytes
Run Code Online (Sandbox Code Playgroud)
据我所知read()应该继续阅读,直到它到达文件的末尾.它是否会在第二次调用时报告文件结束(0)?
也许我错过了一些明显但我看不到的东西.我一遍又一遍地阅读这份文件和这份文件,我找不到我做错了什么.有没有人有任何线索?
编辑
谢谢你的暗示!这是问题中的拼写错误(我已经纠正过了).它在源代码中是正确的.
void read_file(const char filename)
然后:
int fd_in = open(filename, O_RDONLY, 0x00644);
不要忽略编译器警告.我很惊讶这不只是崩溃.
我怀疑字节217是EOF(26,0x1A) - 在Windows文件中可以以"文本"或"二进制"模式打开.在文本模式下,0x1A被解释为EOF.
您需要查看您的打开模式 - O_BINARY.在PHP中,这就是你必须使用模式"rb"(READ BINARY)而不是"R"("R"默认为READ TEXT)的原因.
http://www.mingw.org/wiki/FAQ说标志是O_BINARY(靠近页面底部),所以你需要
int fd_in = open(filename, O_RDONLY | O_BINARY, 0644);
Run Code Online (Sandbox Code Playgroud)
http://cygwin.com/faq.html第5.3段告诉你如何在cygwin中处理这个问题