[英]Why can't I read from a file?
I'm trying to read few bytes from a file and then print them to screen, but the read()
function keeps returning -1 for some reason.我试图从文件中读取几个字节,然后将它们打印到屏幕上,但
read()
函数由于某种原因不断返回 -1。
Here's the code:这是代码:
#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");
}
The output for this is:这个输出是:
File was successfully opened with file descriptor 3.
Error reading the file.
The file I'm trying to read from is definitely bigger than 20 bytes.我试图读取的文件肯定大于 20 个字节。
What could be the problem here?这里可能有什么问题?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.