This simple program, cannot read data using ifstream. The read is always an empty string.
#include <fstream>
#include <string>
#include <iostream>
std::string getFileString(const std::string& path)
{
std::ifstream file(path);
if (!file)
throw std::exception("Cannot Open File");
if (!file.is_open() && !file.good())
throw std::exception("Cannot Open File");
std::string t;
file >> t;
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return content;
}
int main()
{
std::string t = getFileString("C:\\Users\\user\\Documents\\folder\\t1.txt");
return 0;
}
I have tried debugging this for a few hours, and there's no way to fix it. I've tried in new projects to do this exact same thing, and the ifstream doesn't read anything.
I confirmed:
there is data in the file
the path is correct
I am compiling under debug, with debug libraries
I have tried:
std::getline(file, t)
file.getline
using iterators
using the >> operator
No exceptions are thrown (even with ios::failbit and ios::badbit set)
file is good
file.is_open() is true and file.good() is true
When I examine the file stream object in debugger (after constructor call) it appears to be corrupted (the entire buffer is null, bunch of nulls in the pointers, the only valid data is the reference to the file itself).
I have compiled for both win32 and x64 and I get the same result.
I repaired my installation of C++ distributable for VS 2012, and it's the same issue.
I have no idea what to do at this point. I have never seen an issue like this before. I'm beginning to wonder if other std objects are also corrupted like this one. Or maybe it's the C file stream that is corrupted in some shape.
EDIT*** I have removed the arguments, but whatever data is being read is not what is from my file.
ifstream
constructor? Where did you get those from? What does the manual tell you about them? - Kerrek SBstd::ios::failbit | std::ios::badbit
arguments. - user1593881||
instead of&&
in!file.is_open() && !file.good()
. With&&
, both condition need to be true (i.e., file is not open AND file is not good) for the exception to be thrown. - 1201ProgramAlarm