2014-03-30 24 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。我的壞,我**做過**實際上讀取函數原型,但沒有注意到它... 謝謝。 –

相關問題