C++ Ifstream Error Using String as Opening File Path

C++ ifstream error using string as opening file path

Although C++11 defines a std::fstream constructor that accepts a std::string as input, Microsoft's implementation of std::fstream apparently does not:

https://msdn.microsoft.com/en-us/library/a33ahe62.aspx#basic_fstream__basic_fstream

You will have to use the std::string::c_str() method to pass the filename:

fstream inFile(fileName.c_str(), fstream::in);

That being said, consider using std::ifstream instead:

ifstream inFile(fileName.c_str());

C++ ifstream error using string as opening file path.

Change

ifstream file(filename);

to

ifstream file(filename.c_str());

Because the constructor for an ifstream takes a const char*, not a string pre-C++11.

ifstream error using string as opening file path

How std::ifstream finds a file given a path is platform-specific, but on a Unix-like system the string should simply be passed to open.

You might try debugging a direct call to open (from <fcntl.h>), and/or check errno (from <cerrno>) after the ifstream constructor returns.

In any case, the problem is almost certainly either insufficient permissions or a spelling error.

ifstream error using string as opening file path

How std::ifstream finds a file given a path is platform-specific, but on a Unix-like system the string should simply be passed to open.

You might try debugging a direct call to open (from <fcntl.h>), and/or check errno (from <cerrno>) after the ifstream constructor returns.

In any case, the problem is almost certainly either insufficient permissions or a spelling error.

Issue reading file with ifstream using absolute path

It seems zenity, which you use as file chooser, outputs an extra newline after the file name, which you include in the name. In Linux, files can actually contain embedded newline characters in their name, and you actually try to open "test.odin\n" instead of "test.odin".

Why do I get error when ifstream is creating file with string read from keyboard?

[...] in the same directory with main.cpp [...]

It does not really matter where you put the input file relative to the source file.
The file should be in the environment's current working directory when you run the program.



Related Topics



Leave a reply



Submit