Reading from a text file

Mar 8, 2009 at 8:55pm
I am trying to read lines from a text file whose name is passed as a command line argument. I have tried numerous things but have been yet been able to get the file open. I have no compiler issues. The file that I am trying to open is called words.txt and is in the same directory as the cpp. My code is below, thanks for any help.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <sstream>
#include <iostream>
#include <fstream>
#include "HTable.h"

using namespace std;

int main(int argc, char *argv[])
{

	string temp = argv[1];
	cout << temp << endl;
	
	ifstream WordsIn;
	
	
	WordsIn.open(temp.c_str());
	if(WordsIn.is_open()==false)
	{
		cout << "Could not open list of words\n";
	}
	else
	{
             .....
        }
Mar 8, 2009 at 9:11pm
Are you actually passing it as an argument? Also, if the user doesn't input an argument you will be accessing invalid data, so check argc beforehand. Other then that...I don't see anything that's wrong...
Mar 8, 2009 at 10:51pm
I am passing it as an argument: im using cygwin so once i have compiled the program I run it via ./a words.txt

as for checking for invalid data, i will be sure to do that as soon as i get the code working.
Mar 8, 2009 at 11:18pm
I have just tried to open the file not by doing

ifstream WordsIn ("words.txt");

and even that is failing. Any ideas.
Mar 9, 2009 at 12:26am
Try adding / before words.txt or ./
Mar 9, 2009 at 12:34am
Are you sure there is a "words.txt", spelled and capitalized correctly, in the same directory as your executable?

For example:
> ls
a HTable.h Makefile main.cpp words.txt

Your usage is fine:
>./a words.txt


Anyway, I don't use the is_open method but I know that if(WordsIn) is true if the ifstream openned with the ifstream WordsIn("words.txt"); syntax...

Are you sure that it's compiling? Maybe the executable is old... Try:
> rm a
and then make or g++, etc..
Last edited on Mar 9, 2009 at 12:37am
Mar 9, 2009 at 2:55am
the words.txt file is in the same directory and spelled exactly as is in the code, also the executable is current. I have no idea why it won't work because it doesn't seem that complex.
Mar 9, 2009 at 6:38am
Post more information, if possible. Does it compile and then just output "could not open list of words"?
Mar 9, 2009 at 1:57pm
Yes it compiles without error and then says cannot open list of words
Topic archived. No new replies allowed.