我正在尝试开发一个概念验证程序,它打开一个文件,读取一些数据并关闭它,所有这些都不使用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;
}
Run Code Online (Sandbox Code Playgroud)
如果不存在文件,则打开正确打印错误消息.另一方面,如果文件存在,则程序在read()函数处停止,原因不明.对此有何帮助?
由于运算符优先级,这是不正确的:
if ( fp = open ( "test.txt", O_RDONLY ) < 0 )
Run Code Online (Sandbox Code Playgroud)
作为=具有比低优先级<.这意味着,fp将被分配或者0或1取决于结果,open ( "test.txt", O_RDONLY ) < 0.
-1 < 0,1并且fp已分配结果1并输入if分支.N < 0(其中N会大于二因stdin,stdout并stderr占据文件描述符0,1和2),并fp分配0和if没有输入分支.程序然后继续到read()行,但fp具有值0,stdin因此它在等待从中读取内容时停止stdin.改成:
if ( (fp = open ( "test.txt", O_RDONLY )) < 0 )
Run Code Online (Sandbox Code Playgroud)
同样的问题:
while ( num_bytes = read ( fp, &header, 2 ) > 0 )
Run Code Online (Sandbox Code Playgroud)