我想从文件中读取几个字节,然后将它们打印到屏幕上,但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个字节。
这里有什么问题?
为什么使用'read'系列而不是'fread'? – avmohan
当系统调用失败时,您应该检查['errno'](http://man7.org/linux/man-pages/man3/errno.3.html)以查看出了什么问题。使用['strerror'](http://man7.org/linux/man-pages/man3/strerror.3.html)从错误中获取可打印的字符串,或使用['perror'](http:// man7.org/linux/man-pages/man3/perror.3.html)直接打印邮件。 –
@ v3ga,read()有什么问题? –