2015-11-07 99 views
1

我正在嘗試製作一個程序,用於讀取目錄中的所有.txt文件。它使用file->d_name獲得每個文件的名稱,但現在我需要打開這些文件才能使用它們。C:讀取目錄中的所有* .txt文件

#include <dirent.h> 
#include <stdlib.h> 
#include <stdio.h> 

int main (int argc, char *argv[]) { 

    DIR *directory; 
    struct dirent* file; 
    FILE *a; 
    char ch; 

    if (argc != 2) { 
     printf("Error\n", argv[0]); 
     exit(1); 
    } 

    directory = opendir(argv[1]); 
    if (directory == NULL) { 
     printf("Error\n"); 
     exit(2); 
    } 

    while ((file=readdir(directory)) != NULL) { 
     printf("%s\n", file->d_name); 

      // And now???? 

     } 

     closedir(directory); 
    } 
+0

C標準庫有檔案存取功能。你可能會想fopen,fread和fclose。我假設你在問如何讀取文件;你的問題有點不清楚。 –

回答

1

您寫道:目錄項

while ((file=readdir(directory)) != NULL) { 
printf("%s\n",file->d_name); 
    //And now???? 
} 
  1. 檢查是否是一個文件或目錄。如果它不是常規文件,請轉到下一個目錄條目。

    if (file->d_type != DT_REG) 
    { 
        continue; 
    } 
    
  2. 我們有文件。通過組合目錄條目中的目錄名稱和文件名稱來創建文件的名稱。

    char filename[1000]; // Make sure this is large enough. 
    sprintf(filename, "%s/%s", argv[1], file->d_name); 
    
  3. 使用標準庫函數打開並讀取文件的內容。

    FILE* fin = fopen(filename, "r"); 
    if (fin != NULL) 
    { 
        // Read the contents of the file 
    } 
    
  4. 在處理下一個目錄條目之前關閉文件。

    fclose(fin); 
    
+0

你可能想給文件名長度爲'strlen(argv [1])+ strlen(file-> d_name)+ 2',而不是常量1000(假設你使用的是c99或c11)。在堆棧上分配1000個字節可能不是某些系統上的最佳決策。 –

0

我想你需要看file handling in c

while ((file=readdir(directory)) != NULL) { 
    printf("%s\n",file->d_name); 
    //To open file 
    a = fopen("file->d_name", "r+"); //a file pointer you declared 


    }