Hi,

I would like to read a directory, and get all the files in that with some kind of sorting, let us say sort by timestamp.

Can you help me, here is my code so far:

#include <stdio.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <cstdlib>
#include <vector>
#include <string.h>
#include <iterator>
#include <dirent.h>
#include <ctime>
#include <sys/stat.h>

using namespace std;

struct TFile {string name;time_t time;};

bool pred_time(const TFile& x, const TFile& y)
{
  return x.time < y.time;
}

int main()
{
  struct dirent *dirp;

  string filepath = "";
  string line     = "";

  vector< vector< vector<string> > > Data;
  vector<TFile> v;

  string dir = "./TestDir";
  DIR* dp    = opendir( dir.c_str() );
  if (dp != NULL)
  {
    while((dirp = readdir(dp)))
    {
      struct TFile filedata;
      struct stat filestat;
      
      filedata.name = dir + "/" + dirp->d_name;
      if(S_ISDIR(filestat.st_mode))
	continue;
      if (stat(filedata.d_name.c_str(), &filestat) >= 0 && strcmp(dirp->d_name, ".") != 0 && strcmp(dirp->d_name, "..") != 0)
      {
	filedata.time = filestat.st_mtime;
	v.push_back(filedata);
      }
    }
    closedir(dp);
  }

  sort(v.begin(),v.end(),pred_time);

  vector<TFile>::iterator it;
  for (it = v.begin(); it != v.end(); it++)
  {
    char datestring[256];
    time_t time = it->time;
    struct *tm = localtime(&time);
    strftime(datestring, sizeof(datestring), nl_langinfo(D_T_FMT), tm);
    printf("%s %s\n", it->name, datestring);
  }

  return 0;
}

I get these error messages:

ReadDir4.cpp: In function ‘int main()’:
ReadDir4.cpp:44: error: ‘struct TFile’ has no member named ‘d_name’
ReadDir4.cpp:53: error: ‘sort’ was not declared in this scope
ReadDir4.cpp:60: error: invalid type in declaration before ‘=’ token
ReadDir4.cpp:60: error: cannot convert ‘tm*’ to ‘int*’ in initialization
ReadDir4.cpp:61: error: ‘D_T_FMT’ was not declared in this scope
ReadDir4.cpp:61: error: ‘nl_langinfo’ was not declared in this scope
ReadDir4.cpp:62: warning: cannot pass objects of non-POD type ‘struct std::string’ through ‘...’; call will abort at runtime
ReadDir4.cpp:62: warning: format ‘%s’ expects type ‘char*’, but argument 2 has type ‘int’

>>ReadDir4.cpp:44: error: ‘struct TFile’ has no member named ‘d_name’

Lear how to recognize the errors in your program. This one is pretty simple and straight forward. Look at the declaration of TFile, located at the top of your program. Notice that is does not have a member named d_name. Now look at line 44 of your program, where the error was issued. Fix the problem there by replacing stat(filedata.d_name.c_str(), with stat(filedata.name.c_str(), .

After fixing that recompile and do something similar with the remaning errors.

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.