-
Reading in a file
I'm trying to read in a series of text files in c++ but running into a bit of trouble. I've never done this before and I'm trying to follow the guide here: http://www.cplusplus.com/doc/tutorial/files.html
Here's my code:
Code:
#include <cstdlib>
#include <fstream>
#include <iostream>
#include "thread.h"
using namespace std;
int numThreads;
int main(int argc,char* argv[])
{
ifstream in;
string line;
cout << argv[1] << endl;
numThreads = atoi(argv[1]);
cout << "Number of threads: " << numThreads << endl;
for(int i=2;i<argc;i++)
{
cout <<"Opening:" << argv[i] << endl;
in.open(argv[i]);
while(!in.eof())
{
cout << "A LINE" << endl;
getline(in,line);
cout << line << endl;
}
in.close();
}
return 0;
}
Just to explain what's happening...I'm passing in a series of command line arguments, the first of which is the number of arguments I'm passing, and the other ones are files. It works fine until I get to the while loop. It just keeps printing "A LINE" over and over and never prints anything from the file.
-
I get:
Code:
Opening:files.cpp
A LINE
#include <cstdlib>
A LINE
#include <fstream>
A LINE
#include <iostream>
A LINE
A LINE
using namespace std;
A LINE
A LINE
int numThreads;
A LINE
A LINE
int main(int argc,char* argv[])
A LINE
{
A LINE
ifstream in;
A LINE
string line;
A LINE
cout << argv[1] << endl;
A LINE
numThreads = atoi(argv[1]);
A LINE
cout << "Number of threads: " << numThreads << endl;
A LINE
for(int i=2;i<argc;i++)
A LINE
{
A LINE
cout <<"Opening:" << argv[i] << endl;
A LINE
in.open(argv[i]);
A LINE
while(!in.eof())
A LINE
{
A LINE
cout << "A LINE" << endl;
A LINE
getline(in,line);
A LINE
cout << line << endl;
A LINE
}
A LINE
in.close();
A LINE
}
A LINE
return 0;
A LINE
}
A LINE
A LINE
I suppose you could check to make sure (1) you provide all the filenames you claim you do and (2) they can each be opened.
-
It looks like you passed the file name that you are running as an argument to be opened?
Anyways, it looks the files aren't being opened. I guess I never really considered where the files are. They are in my src code directory but I'm not really sure where they are supposed to go. I'm running KDevelop on Ubuntu but I don't think that helps any
-
Figured it out. For anyone who cares, the home directory is under debug/src
-
Well, I had to use something. But the files need to be in the directory you are running from, or you need to specify the full path.