我想使用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 (交友-特殊)‘。
我看到的奇怪的行为是,并不是所有的内容都被阅读了。例如,我有一个文件
05.01.2012 12:28 15.838 hello.exe
当我试着读它时,我得到了:
Read 216 bytes
Read 0 bytes
据我所知,read()应该一直读到文件的末尾。它是否在第二次调用时报告文件(0)的结尾?
也许我错过了一些显而易见的东西,但我看不见。我一遍又一遍地读本文件和本文件,我找不到我做错了什么。有人有线索吗?
编辑
谢谢你的暗示!这是问题中的一个错误(我已经改正了)。它在源代码中是正确的。
发布于 2012-01-05 14:30:59
我怀疑字节217是EOF (26,0x1A) -在Windows文件可以打开“文本”或“二进制”模式。在文本模式中,0x1A被解释为EOF。
您需要查看您的开放模式- O_BINARY。在PHP中,这就是为什么必须使用模式"rb“(读取二进制)而不是"R”(默认为读取文本)来打开的原因。
http://www.mingw.org/wiki/FAQ说标志是O_BINARY (接近页面底部),所以您需要
int fd_in = open(filename, O_RDONLY | O_BINARY, 0644);
http://cygwin.com/faq.html第5.3段告诉您如何在cygwin中处理这一问题
发布于 2012-01-05 13:42:08
void read_file(const char filename)
然后以后:
int fd_in = open(filename, O_RDONLY, 0x00644);
不要忽略编译器警告。我很惊讶这不仅仅是撞车。
发布于 2012-01-05 13:52:22
您可能想尝试在公开调用中使用O_RDONLY | O_BINARY
或O_RDONLY | O_NOTRANS
。如果不指定O_BINARY或O_NOTRANS,则可以以文本模式打开文件,读取将在首次遇到EOF字符时停止。
https://stackoverflow.com/questions/8743467
复制相似问题