[英]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???? }
檢查目錄條目是文件還是目錄。 如果它不是常規文件,請繼續下一個目錄條目。
if ( file->d_type != DT_REG ) { continue; }
我們有文件。 通過組合目錄名稱和目錄條目中的文件名稱來創建文件的名稱。
char filename[1000]; // Make sure this is large enough. sprintf(filename, "%s/%s", argv[1], file->d_name);
使用標准庫函數打開和讀取文件的內容。
FILE* fin = fopen(filename, "r"); if ( fin != NULL ) { // Read the contents of the file }
在處理下一個目錄條目之前,請關閉文件。
fclose(fin);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.