Hi everyone,

I have a directory that have 100s of txt files. (Folder is Data_Sets_30)

I want to open txt files one by one and get values and close the file and open next txt file get values and close the file and continue like that.

I started to code but I don't know exactly how to do it.

#include <dirent.h>
struct dirent *entry;
DIR *dp;
dp = opendir("C:/Users/acer/Documents/Visual Studio 2010/Projects/DevC++30/DevC++/Data_Sets_30");
if (dp == NULL)
{
    perror("Error Occurred");
    return -1;
}
while((entry = readdir(dp)))
{
... I don't know that part
}

http://www.linuxquestions.org/questions/programming-9/c-list-files-in-directory-379323/

Copied from above link:

#include <sys/types.h>
#include <dirent.h>
#include <errno.h>
#include <vector>
#include <string>
#include <iostream>

using namespace std;

/*function... might want it in some class?*/
int getdir (string dir, vector<string> &files)
{
    DIR *dp;
    struct dirent *dirp;
    if((dp  = opendir(dir.c_str())) == NULL) {
        cout << "Error(" << errno << ") opening " << dir << endl;
        return errno;
    }

    while ((dirp = readdir(dp)) != NULL) {
        files.push_back(string(dirp->d_name));
    }
    closedir(dp);
    return 0;
}

int main()
{
    string dir = string(".");
    vector<string> files = vector<string>();

    getdir(dir,files);

    for (unsigned int i = 0;i < files.size();i++) {
        cout << files[i] << endl;
    }
    return 0;
}

excually I couldn't understand the codes. Could you explain part by part ?

At line 12 of your code, you wrote "I don't know that part" (sorry, the line numbers won't match up here):

while((entry = readdir(dp)))
{
    ... I don't know that part
}

The responder provided code that solves your problem, specifically at line 21:

while ((dirp = readdir(dp)) != NULL) {
    files.push_back(string(dirp->d_name));
}

Read one line at a time. Understand what that line does. Then move to the next line. If you can't figure out what a particular function does, look it up. Then go back and look at a block of lines (surrounded by {}) and understand what the block does, and so on, until you understand the whole program. Unfortunately, there's really no good alternative that will help you learn programming. You can try to delay it, and get people to write specific code for you for a while, but sooner or later you'll actually want to be able to do it yourself, and to do that, you'll have to learn first. DaniWeb is here to help! ... as are plenty of other online resources, but I like this one. :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.