2016-03-15 267 views
-2

我正在通過參數獲取文件並返回其信息和名稱的程序。我得到錯誤錯誤的文件描述。我的代碼如下所示:錯誤的文件描述符C

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/stat.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <fcntl.h> 
#include <time.h> 

int main(int argc, char *argv[]){ 
    if(argc < 2){ 
     printf("Error"); 
     return 1; 
    } 
    else 
    { 
     int i; 
     for(i=1;i<argc;i++) 
     { 
      int file = 0; 
      file = open(argv[i], O_RDONLY); 
      if(file == -1) 
      { 
       close(file); 
       return 1; 
      } 
      else 
      { 
       struct stat info; 
       if(fstat(file, &info) < 0) 
       { 
        close(file); 
        return 1; 
       } 
       else 
       { 
        printf("Status information for %s\n",argv[i]); 
        printf("Size of file: %d \n", info.st_size); 
        printf("Number of connections: %d\n", info.st_nlink); 
        printf("inode: %d\n", info.st_ino);     
        printf("Last used : %s", ctime(&info.st_atime)); 
        printf("Last change : %s", ctime(&info.st_mtime)); 
        printf("Last status of change : %s", ctime(&info.st_ctime)); 
        printf("ID owner : %d\n", info.st_uid); 
        printf("ID group : %d\n", info.st_gid); 
        printf("ID device : %d\n", info.st_dev); 
        printf("Security : :"); 
        printf((S_ISDIR(info.st_mode)) ? "d" : "-"); 
        printf((info.st_mode & S_IRUSR) ? "r" : "-"); 
        printf((info.st_mode & S_IWUSR) ? "w" : "-"); 
        printf((info.st_mode & S_IXUSR) ? "x" : "-"); 
        printf((info.st_mode & S_IRGRP) ? "r" : "-"); 
        printf((info.st_mode & S_IWGRP) ? "w" : "-"); 
        printf((info.st_mode & S_IXGRP) ? "x" : "-"); 
        printf((info.st_mode & S_IROTH) ? "r" : "-"); 
        printf((info.st_mode & S_IWOTH) ? "w" : "-"); 
        printf((info.st_mode & S_IXOTH) ? "x" : "-"); 
        if(S_ISREG(info.st_mode)){ 
         printf("\nFile is regular\n"); 
        } 
        else if(S_ISDIR(info.st_mode)){ 
         printf("\nFile is a directory\n"); 
        } 
        printf("\n===================================\n"); 
        close(file); 

       } 
      } 
     } 
    } 
    return 0; 
} 

當我運行這樣的程序,例如: ./program somefile 我得到這個回報 - >錯誤的文件描述符

+1

嘗試來這裏之前先google搜索,有噸answeres在那裏 – redFIVE

+3

如果'open'失敗,爲什麼你會嘗試'close'結果呢?它僅在錯誤時返回-1,因爲_can't_不是有效的文件描述符,所以_cannot_對'close'有效。 – Useless

+1

你從哪裏看到這個錯誤? –

回答

2

的問題是在這裏:

 file = open(argv[i], O_RDONLY); 
     if(file == -1) 
     { 
      close(file); 
      return 1; 
     } 

因爲當file==-1,它不是一個有效的文件描述符傳遞給close

可以安撫自己,這是確定不叫close在這個分支,因爲如果open失敗,有沒什麼close擺在首位。

順便說一句,close也有一個返回值,都openclose設置errno如果他們失敗:您可以檢查,並記錄,所有這些。事實上,幾乎所有的代碼最終都是錯誤檢查/處理,這是其他語言(如C++)引入異常的動機之一。

int file = open(argv[i], O_RDONLY); 
if(file == -1) { 
    perror("open failed"); 
    return 1; 
} 
struct stat info; 
if (fstat(file, &info) < 0) { 
    perror("fstat failed"); 
    if (close(file) < 0) { 
     perror("close failed"); 
    } 
    return 1; 
}