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
When Is a Vtable Created in C++
How to Block Running Two Instances of the Same Program
How to Read a File into Vector in C++
Template Specialization Based on Inherit Class
How to Iterate Over a Std::Tuple in C++ 11
Of Memory Management, Heap Corruption, and C++
Avx2: Computing Dot Product of 512 Float Arrays
What's the Easiest Way to Generate Xml in C++
C++ Opencv Image Sending Through Socket
C++ Format MACro/Inline Ostringstream
What Does 'Return *This' Mean in C++
Qtcpsocket: Reading and Writing
Boost-Python How to Pass a C++ Class Instance to a Python Class
Project Error: Unknown Module(S) in Qt: Webkitwidgets
Loop with a Zero Execution Time
Convert Eigen Matrix to C Array
How to Force Gcc to Assume That a Floating-Point Expression Is Non-Negative