简体   繁体   中英

C: Read all *.txt files in a directory

I'm trying to make a program that reads all .txt files in a directory. It obtains the name of each file using file->d_name , but now I need to open the files to work with them.

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

You wrote:

 while ((file=readdir(directory)) != NULL) { printf("%s\\n",file->d_name); //And now???? } 
  1. Check whether the directory entry is a file or a directory. If it is not a regular file, move on to the next directory entry.

     if ( file->d_type != DT_REG ) { continue; } 
  2. We have file. Create the name of the file by combining the directory name and the file name from the directory entry.

     char filename[1000]; // Make sure this is large enough. sprintf(filename, "%s/%s", argv[1], file->d_name); 
  3. Use standard library functions to open and read the contents of the file.

     FILE* fin = fopen(filename, "r"); if ( fin != NULL ) { // Read the contents of the file } 
  4. Close the file before processing the next directory entry.

     fclose(fin); 

I think you need to see 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


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM