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’