c - 为什么我无法读取文件?

标签 c file

我试图从文件中读取几个字节,然后将它们打印到屏幕上,但由于某种原因,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 的参数,第一个参数应该是打开的文件描述符,而不是文件名;

int ret_code=read(file_desc,buff,20);

...应该工作得更好。

关于c - 为什么我无法读取文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22745879/

相关文章:

c - 如何创建一个包含 0 到 1000 之间所有整数的数组?

c - 添加学生人数

c - 有没有什么方法可以等到任务在 intel arch 中捕获 SIGALRM 信号?

c - 用C将文本写入.txt文件

c - 变长数组如何支持数值处理?

c - C中的布莱克曼-哈里斯

c# - 如何在 MVC .Net 中通过邮件发送文件(位于 URL)作为附件

python - 将单个字节写入 python 3.x 中的文件

java - 是否可以将对象存储到 Java 中的属性文件?

file - 类型错误 : invalid file: When trying to make a file name a variable