The following function works fine, showing a text file line by line to stderr:
void load_text(std::string path){
ifstream f(path);
char linebuff[100];
linebuff[99] = 0;
while(!f.eof()){
f.getline(linebuff, 99);
std::cerr<<linebuff<<std::endl;
}
f.close();
}
Now, when the main function returns, it throws the following acces violation error:
Unhandled exception at 0x77e58dc9 in app.exe: 0xC0000005: Access violation writing location 0x00000014.
Oddly enough, creating an ifstream, closing it and returning also throws the error
//This also crashes when returning from main
void load_text(std::string path){
ifstream f(path);
f.close();
}
Any idea why this happens?
Edit:
The main function (as it is compiled), this actually works provided you create a new project, the difference with the actual program are a lot of never called, never used functions and classes
Right now I'm in the 'cannot reproduce' stage:
#include <fstream>
#include <string>
#include <iostream>
//Using SDL for plotting
#ifdef WIN32
#pragma comment(lib, "SDL")
#pragma comment(lib, "SDLMain")
#pragma comment(lib, "SDL_image")
#endif
int fn(std::string path){
std::ifstream f(path);
char linebuff[100];
linebuff[99] = 0;
while(!f.eof()){
f.getline(linebuff, 99);
std::cerr<<linebuff<<std::endl;
}
f.close();
return 0;
}
int main(int argc, char** argv){
fn("sscce.cpp");
return 0;
}
while (!eof())
is wrong.. And why are you reading in C strings?std::string line
andwhile (std::getline(f, line))
for the loop condition,f.eof()
is almost never what you want to do), this looks ok (esp the latter). You say the exception is aftermain()
returns, but don't bother showing us what is inmain()
on either side of this proc call. Please post a SSCCE including amain()
that reproduces the problem?#ifdef
is wrong, it should be#ifdef _WIN32
. Note the leading underscore.