I try to read filenames in a directory and after store them in an char array.
My problem is that I can not store the filenames and I don't understand the error messages the compiler gives.
I'm new to C++ and I hope that someone can help me to correct my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <list>
#include <iostream>
#include <fstream>
#include <string>
#include <istream>
#include <sstream>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
usingnamespace std;
int main(void)
{
int j;
int n_files;
string temp_cin;
cout << "number of files in the directory:" << flush;
getline( cin, temp_cin);
stringstream converted(temp_cin); // Converts the string 'temp_cin' into ??
converted >> n_files; // writes converted into n_files
cout << n_files << endl;
char* FilePath[n_files][40];
int getFilename(char FilePath[n_files][40]);
getFilename(FilePath[n_files][40]);
while(j <= n_files-1)
{
cout << FilePath[j] << endl;
}
return 0;
}
int getFilename(char FilePath[][40])
{
ifstream fin;
string dir, filepath;
int num;
DIR *dp;
struct dirent *dirp;
struct stat filestat;
string temp_cin;
int n_files;
int j=0;
cout << "directory to get files of: " << flush;
getline( cin, dir ); // gets everything the user ENTERs
cout << "number of files in the directory:" << flush;
getline( cin, temp_cin);
stringstream converted(temp_cin); // Converts the string 'temp_cin' into ??
converted >> n_files; // writes converted into n_files
cout << n_files << endl;
dp = opendir( dir.c_str() );
if (dp == NULL)
{
cout << "BAD" << endl;
}
while ((dirp = readdir( dp )))
{
filepath = dir + "/" + dirp->d_name;
FilePath[j] = strcpy(filepath.c_str);
// If the file is a directory (or is in some way invalid) we'll skip it
if (stat( filepath.c_str(), &filestat )) continue;
if (S_ISDIR( filestat.st_mode )) continue;
// Endeavor to read a single number from the file and display it
fin.open( filepath.c_str() );
if (fin >> num)
cout << filepath << ": " << num << endl;
fin.close();
cout << filepath << endl;
j++;
}
closedir( dp );
return 0;
}
I get the following error messages:
- at line 36: array bound is not an integer constant before >>]<< token
- argument of type >> const char* (std::basic_string<char>::)()const<< to >>char<< does not fit
Line 36 is a prototype declaration. You need it, so that the compiler knows, that there exists a function GetFilename. There are two ways, so that the compiler can know:
- move function GetFilename before main
- use a prototype declaration
A prototype declaration you don't make inside a function;
Acutally I've no idea. I'm new to C++ and I tried what I thought best. I'm not sure wheater this is possible and after reading the tutorial I'm not further therefore I posted my problem here.