ifstream not working

Started by
9 comments, last by shuma-gorath 10 years, 4 months ago

in.open("test.txt", ios::in | ios::binary | ios::ate);

if (in.is_open())
cout << "File opened" << endl;

the test.txt exists and it has text in it,yet,i see no file opened string. What could be the problem?

Advertisement

Is the file in the right place? It has to be in the root of the working directory.

its in the exact place as the exe( i tested it without debugging),and still,i see no text.

But what about the working directory? If, for example, you run the program from Visual Studio, the working directory is by default the project directory, so that's where you have to put the file.

tried....still nothing....

Try something like this, so you get a meaningful error message:
#include <iostream>
#include <fstream>
#include <cerrno>

int main() {
  std::ifstream in;
  in.open("test.txt", std::ios::in | std::ios::binary | std::ios::ate);

  if (in.is_open())
    std::cout << "File opened\n";
  else
    std::cout << std::strerror(errno) << '\n';
}

std::string ExePath()
{
	char buffer[_MAX_PATH];
	GetModuleFileName(NULL,buffer, MAX_PATH);
	string::size_type pos = string(buffer).find_last_of("\\/");
	return string(buffer).substr(0, pos);
}


int main(){

try{
		string path = ExePath() + "\\A.txt";
		ifstream          in;
		in.exceptions(std::ios::failbit);
		cout << path.c_str() << endl;
		in.open(path);
	}
	catch (const std::exception & ex) {

		cerr << strerror(errno);
	}

}

output: c:\users\enjoydrama\documents\visual studio 2013\Projects\Raisa\Release\A.txt
No such file or directory

I went to the path,and A.txt exists!

GetModuleFilename returns the path to the executable. You need the working directory, look up GetCurrentDirectory. The path to the executable and the working directory are not necessarily the same.

std::string ExePath()
{
    char buffer[_MAX_PATH];
    GetCurrentDirectoryA(MAX_PATH,buffer);
    string::size_type pos = string(buffer).find_last_of("\\/");
    return string(buffer).substr(0, pos);
}

Getting the path to the executable fails as expected, and getting the working directory works as expected, when I run it from Visual Studio.

brotherbob...the release folder had a in it too. Anyway,i tried with getcurdir too,the same happens.

UPDATE:

this works: ifstream binary_file("c:\'a.txt", ios::in | ios::binary | ios::ate);

this doesn't: fstream binary_file("c:\'a.txt", ios::out | ios::binary | ios::app);

when i say it doesn't i mean it can't find the file.

With the program, try creating a dummy file by opening an ofstream, and creating a new empty file that didn't exist before. If it doesn't exist where you thought it did, then that solves one problem. If it doesn't exist at all, then that's another problem. If it puts it exactly where you thought, then carry on with your debugging.

This topic is closed to new replies.

Advertisement