0

Im trying to go through a folder and read all files inside the folder. Reading in one specific file is not a problem, but I cant seem to find a good solution for reading all the files. I have been searching and havent found anything that worked. So, how would i be able to load all files? The code that i have now:

DIR *dir;
struct dirent* lsdir;

dir = opendir("C:\\Users\\Utilizador\\Desktop\\La voz de galicia\\Voz\\Nova pasta");

while ( ( lsdir = readdir(dir) ) != NULL )
{
    printf ("%s\n", lsdir->d_name);
    char tes[260];
    strcpy(tes,lsdir->d_name);
    FILE *f = fopen(tes,"r");
    if(f==NULL){printf("erro");}
    fclose(f);
}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • 4
    what's wrong with the code you've posted? You might find the [filesystem](https://en.cppreference.com/w/cpp/filesystem) library easier to use – Alan Birtles Jan 28 '22 at 11:02
  • The file doesnt open im not sure why im guessing that the fopen(tes,"r"); isnt working properly or im not doing it properly – diogo franco Jan 28 '22 at 11:08
  • The name specified by `lsdir->d_name` is *relative* to the path associated with `dir`. You need to concatenate them to specify the full path. I'd echo the sentiments of Alan Birtles though: make use of [`std::filesystem`](https://en.cppreference.com/w/cpp/filesystem) instead. – G.M. Jan 28 '22 at 12:02
  • Note that `d_name` is a relative path to your starting directory so won't be openable unless your current working directory is the same directory, you need to concatenate the two paths together. You don't need to install anything to use filesystem if you are using a reasonably recent compiler. There's an example in the [documentation](https://en.cppreference.com/w/cpp/filesystem/directory_iterator) – Alan Birtles Jan 28 '22 at 12:03
  • You should try something like this: https://stackoverflow.com/questions/53471134/opening-files-with-while-loop-c/53471288 – Douglas Cunha Jan 28 '22 at 12:03
  • @DouglasCunha A Q/A for C is not the best link / hint. C++ meanwhile has something much better in its standard library. – Scheff's Cat Jan 28 '22 at 12:14
  • @Scheff'sCat he is using C in there, for some reason. That's why I posted the C link. – Douglas Cunha Jan 29 '22 at 13:05

0 Answers0