我试图从文件中读取几个字节,然后将它们打印到屏幕,但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个字节 这可能是什么问题?
答案 0 :(得分:4)