【发布时间】:2013-04-12 15:43:28
【问题描述】:
我正在尝试开发一个概念验证程序,它可以打开文件、读取一些数据并关闭它,所有这些都不需要使用 fopen/getc/fclose 函数。相反,我使用的是低级别的打开/读取/关闭等价物,但没有运气:
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
int main ( int argc, char **argv ) {
int fp;
ssize_t num_bytes;
if ( fp = open ( "test.txt", O_RDONLY ) < 0 ) {
perror("Error opening file");
return 1;
}
char header[2];
while ( num_bytes = read ( fp, &header, 2 ) > 0 )
printf("read %i bytes\n", num_bytes);
printf("done reading\n");
close ( fp );
return 0;
}
如果文件不存在,正确打开会打印错误消息。另一方面,如果文件存在,程序会在 read() 函数处停止,没有明显的原因。有什么帮助吗?
【问题讨论】: