简体   繁体   中英

Receiving segmentation fault when trying to read from file in dev c++ mingw 4.8.1

I'm trying to read characters from file but i receive a segmentation fault when i have variables declared outside main. If i delete them and try to read from file, everything works smooth. I am using dev c++ 5.7.1 with mingw 4.8.1 the portable version.

I've isolated the problem to just having a few variables declared and the file reading code. This piece of code comes from a bigger app that i am trying to develop(i am learning game development on my own).

#include <iostream>    
#include <fstream>    
bool running = true;  
bool musicPlaying = true;  
bool read = false;  
int levelNumber;  
int barWidth = 40;  
int barHeight = 10;  
float timeElapsed;  

int main(int argc, char** argv) {    
    std::ifstream file;
    file.open("test.txt");
    std::cout<<file.is_open()<<std::endl;
    char c;
    while(!file.eof()){  
        file.get(c);  
        std::cout<<c;  
    }  
    return 0;  
}

I get the output: 1, the file is open. But no character is read from file. Debug information

Why is this happening?

As per your answer to my comment, declaring bool read overrides read function which is used by the fread . Either rename it or move it to another namespace or class.

None of my compilers could reproduce the same issue. And it's very strange behavior because at least the declaration of 'read' should be the same as the original one for a proper override. Maybe your stdlib is calling read in a different way.

Welcome to StackOverflow...

Firstly, like said your compiler is VERY old. version 4.8.1, while current G++ is version 9.2.

Try to prevent using global variables. It is allowed, but not nice encapsulated design. They are not stored in stack or normal heap, but in some obscure section in memory.

Anyhow, you didn't share test.txt, so I made my own containing

acb

And cleaned your code

#include <iostream>    
#include <fstream>    
int main() {
    std::ifstream file;
    file.open("test.txt");
    std::cout << file.is_open() << '\n';
    char c;
    while (file >> c) std::cout << c;
}

And my output is

1
abc

Even though you're original code reads past the end of the file, I would really expect some output at least. Compilers get updated all the time. Maybe you're actually running into an old bug... You REALLY should update

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM