2015-11-07 180 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 


    }