954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

problem opening files

Hey guys I am using code that does the following:

cin.ignore(); 
cin.getline(file, 250);

ifstream test;

  test.open (file);

	if (test.fail())
		{
		  cout<<"error"<<endl;

		  exit(1);
	     }

...


The problem is that if a file name is entered that does not exist for example c:\\fred.txt the error message will not appear and the txt file fread will be created, but if I enter "c:\\fred.txt" the code seems to work, but I have created similar code before using cin.getline and the quotes were not needed. Any ideas what I have done wrong?

Thanks.

Jon182
Junior Poster in Training
91 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
 

when you enter the filename from the keyboard do not use double backslash -- double slashes are only needed for string literals in your program. So you should type c:\fred.txt , only one backslash. Reason: the compiler does not interpret anything you enter from the keyboard, it only interprets string literals.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 

Hi thanks for your reply but when i do this I still have the same problem.

Jon182
Junior Poster in Training
91 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
 

then the problem is elsewhere. try test.is_open() instead of if test.fail(). Use your compiler's debugger and look at what exactly is in the file buffer, or use cout to display it.

Ancient Dragon
Retired & Loving It
Team Colleague
30,049 posts since Aug 2005
Reputation Points: 5,662
Solved Threads: 2,343
 
then the problem is elsewhere. try test.is_open() instead of if test.fail(). Use your compiler's debugger and look at what exactly is in the file buffer, or use cout to display it.

Hi thanks again for your reply, when i use test.is_open() it doesn't find any file even if it exists.

Jon182
Junior Poster in Training
91 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
 

I have managed to solve the problem by using ios::nocreate, but as I used ifstream I thought I shouldn't have to use this, any ideas? Thanks.

Jon182
Junior Poster in Training
91 posts since Jul 2005
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You