簡體   English   中英

C:讀取目錄中的所有* .txt文件

[英]C: Read all *.txt files in a directory

我正在嘗試制作一個程序,該程序可以讀取目錄中的所有.txt文件。 它使用file->d_name獲取每個文件的名稱,但是現在我需要打開文件來使用它們。

#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);
    }

你寫了:

 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); 

我認為您需要在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


    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM