2014-03-30 94 views
-2

我想从文件中读取几个字节,然后将它们打印到屏幕上,但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

为什么使用'read'系列而不是'fread'? – avmohan

+1

当系统调用失败时,您应该检查['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)直接打印邮件。 –

+0

@ v3ga,read()有什么问题? –

回答

4

如果您查看read的参数,第一个参数应该是打开的文件描述符,而不是文件名;

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

...应该更好地工作。

+2

哇,这个网站上的许多问题,从人们不需要2秒读取函数原型。 smh ... – user457015

+0

OMG。我的坏,我**做过**实际上读取函数原型,但没有注意到它... 谢谢。 –

相关问题