我试图从文件中读取几个字节,然后将它们打印到屏幕上,但由于某种原因,read()
函数始终返回 -1。
代码如下:
#include<stdio.h>
#include<sys/types.h>
#include<fcntl.h>
#include<stdlib.h>
int main(int argc, char* argv[]) {
char buff[100];
int file_desc=open(argv[1], O_RDONLY);
if (file_desc<0) {
printf("Error opening the file.\n");
exit(-1);
}
printf("File was successfully opened with file descriptor %d.\n", file_desc);
int ret_code=read(argv[1],buff,20);
if (ret_code==-1) {
printf("Error reading the file.\n");
exit(-1);
}
int i;
for (i=0; i<20; i++) {
printf("%c ",buff[i]);
}
printf("\n");
}
输出为:
File was successfully opened with file descriptor 3.
Error reading the file.
我尝试读取的文件肯定大于 20 个字节。
这里可能出现什么问题?
最佳答案
关于c - 为什么我无法读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22745879/