Gomes
Gomes

Reputation: 11

Know how many txt there are in a directory

i am trying to do a program that check a directory and tell me how many txt already exist so i can write a new one sequentially. What is the best way to do that, and how i do that?

Sorry for my poor english

Upvotes: 1

Views: 94

Answers (2)

alex01011
alex01011

Reputation: 1702

As Barmar suggested, you can use the functions opendir() to open the desired directory and readdir() to read its content. readdir() returns a pointer to a dirent struct. More about the struct here. You can later use strrchr() to find the last occurence of . and strcmp() to see if you have a match.

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

int main(void)
{
    int txt_count = 0;
    DIR *pdir = NULL;
    struct dirent *dp = NULL;
    char *dir = "."; /* current directory, modify to match your dir */
    char *type = NULL;

    pdir = opendir(dir); /* opens directory dir */

    if (!pdir) /* check if failed to open */
    {
        fprintf(stderr, "Can't open dir <%s>\n", dir);
        exit(EXIT_FAILURE);
    }

    while ((dp = readdir(pdir))) /* reading contents until NULL */
    {
        type = strrchr(dp->d_name, '.'); /* get a pointer to the last occurence of '.' in filename */

        if (type != NULL && !strcmp(type, ".txt")) /* compare with ".txt",check type for NULL if not found */
        {
            txt_count++;
        }
    }

    printf("Total txt files in directory </%s> --> %d\n", dir, txt_count);

    return 0;
}

Upvotes: 1

VictorJimenez99
VictorJimenez99

Reputation: 375

You can use the dirent header to accomplish this task.

you should iterate through every file in the folder, and then you should just do string manipulation, to get the extension of each file.

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



int main() 
{
    const char *dir = ".";//current dir
    printf("opening folder\n");
    DIR *root_folder = opendir(dir);
    if(root_folder == 0) {
        printf("Error opening file");
        return -1;
    }
    struct dirent *file;

    while((file = readdir(root_folder)) != NULL) {
        if(strcmp(file->d_name, ".") == 0 || strcmp(file->d_name, "..") == 0)
            continue;
        printf("%s\n", file->d_name);
        //you can work with the names here
    }
}


Upvotes: 1

Related Questions