Trouble reading from a file

Ok, I'm trying to iterate through all files in a directory to be used as arguments for another program. Trouble is, I am only getting the first letter of all the files in the directory, not name of the file. I am in Linux, so I pipe the command ls -1, to get directory listing line by line, into a text file, then read it. My fscanf must be wrong?

#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include <string>
#include <stdio.h>

using namespace std;

FILE *reader;

int main(int argc, char** argv) {
char line[80];
char source;
source = *argv[1];

system("ls -1 > directory"); //get contents of directory
system("ls -1"); //display contents of directory(testing)

reader = fopen("directory", "r");

while(fgets(line, 80, reader) != NULL)
{

char file;
fscanf(reader, "%s", &file);

time_t startTime;
time_t endTime;
double runTime;
startTime = time (NULL);

cout<<file<<"\n";
system(string(source + " /home/chris/Desktop/Datasets/ " + file).c_str());

endTime = time (NULL);
runTime = difftime(endTime, startTime);

//cout << endl << "The run time is: " << runTime << " seconds" << endl;
}

fclose(reader);
return 0;
}

source and file must be strings. A char is - as the name implies - just a single character.
And don't use fopen/fgets/fscanf/system in C++ programs.

1
2
3
4
5
6
7
8
9
string source=argv[1];
[...]
ifstream file("directory");
string line;
while(getline(file,line))
{
  [...]
  system((source+" /home/chris/Desktop/Datasets/ "+line).c_str());
}


To properly enumerate files in a directory, see man opendir. Or better yet:
http://www.boost.org/doc/libs/1_43_0/libs/filesystem/doc/index.htm
I will look into opendir. I had seen the boost.Filesystem, but did not want to use it since it is not yet part of the standard C++ library. Thanks for your help.
Last edited on
opendir is not part of the C++ standard library either.
And Boost.Filesystem is portable, unlike opendir.
Thanks Athar, I appreciate the help. I'm new to C++, as you can tell. Spoiled by Java I guess :)
Topic archived. No new replies allowed.