Picking up a file in a folder

Asked

Viewed 52 times

-1

I need to take a file with certain extension to open in fopen, but do not know the name of the file, just know that it is in the same folder as main, would have any way inside the main to know which files in the same folder of main contain the extension I need? Ex: in the folder is the main. c and a test.txt (in case I don’t know the file name, only that it is .txt), and would like to open the test.txt in main by fopen (or if you have another command). I hope that has been made clear, I thank you in advance.

1 answer

1


In this example I have the code in the folder: "/home/Ricardo/Desktop/test/"

I want to read the . txt files in the folder: "/home/Ricardo/Desktop/test/txtfolder"

In this folder I have other files that are not '.txt'

Diretorio que pretendo inspecionar

#include <dirent.h>
#include <stdio.h>
//#include <errno.h>
//#include <sys/stat.h>
#include<string.h>
int main(void)
{
    DIR *d;
    struct dirent *dir;
    
    //Diretoria onde estao os ficheiros .txt
    char path[1000]="/home/ricardo/Desktop/teste/txtfolder";
    
    d = opendir(path);
    char full_path[1000];
    if (d)
    {
        while ((dir = readdir(d)) != NULL)
        {
            //Verifica se é um ficheiro regular.
            if(dir->d_type==DT_REG)
            {
                full_path[0]='\0';
                strcat(full_path,path);
                strcat(full_path,"/");
                strcat(full_path,dir->d_name);
                printf("\n\n%s\n",full_path);
        
                //Verifica se o ficheiro é '.txt'
                if(strstr(dir->d_name, ".txt") != NULL) 
                {
                      printf("%s\n",dir->d_name);
                }
        
            }
        }
        closedir(d);
    }
    return(0);
}







 
  • I think I understand, thank you

  • Validates if it answers your question, accepts the answer as valid and gives up vote. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.