简体   繁体   English

为什么我不能从文件中读取?

[英]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?这里可能有什么问题?

If you look at the parameters for read , the first parameter should be the open file descriptor, not the file name;如果查看read的参数,第一个参数应该是打开的文件描述符,而不是文件名;

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

...should work better. ......应该工作得更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM