Issue accessing files using dirent.h

I'm trying to read in every text file from a specified directory and perform some functions on each file. Problem is, I don't seem to be reading anything from the files. The directory access works, as I can alter the code to list all the files in the directory without any problems. I just seem to have issues when it comes to actually accessing each individual file for processing.

Here is a condensed version of my program with pertinent code included....

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int main(int argc, char *argv[])
{
    DIR *dirp;
    char buffer[256];
    strcpy(buffer, argv[1]); //getting the directory from the command line

    //here i have a check to make sure the directory is opened successfully

    ifstream fin;

    while(dptr = readdir(dirp))
    {
        if ( //file is not a root directory file)
        {
            fin.open(dptr->d_name);

            //do stuff with files here. putting a simple read in for this 
            //example

            string s;
            fin >> s;
            cout << s << endl;
        }
        fin.close();
    }
    closedir(dirp);

    return 0;
}


My output from this is just a blank line for every file in the directory, even though the files have text in them.

Any hints or suggestions would be much appreciated.


EDIT: I managed to figure it out. For anybody that is curious, I had to create a string that included the file path + the file name, and open the files using that string.

Corrected code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int main(int argc, char *argv[])
{
    DIR *dirp;
    char buffer[256];
    strcpy(buffer, argv[1]); //getting the directory from the command line
    string holder = buffer;

    //here i have a check to make sure the directory is opened successfully

    ifstream fin;

    while(dptr = readdir(dirp))
    {
        if ( //file is not a root directory file)
        {
            string filepath = holder + "/" dptr->d_name;

            fin.open(filepath.c_str());

            //do stuff with files here. putting a simple read in for this 
            //example

            string s;
            fin >> s;
            cout << s << endl;
        }
        fin.close();
    }
    closedir(dirp);

    return 0;
}
Last edited on
Topic archived. No new replies allowed.