[英]Receiving segmentation fault when trying to read from file in dev c++ mingw 4.8.1
我正在嘗試從文件中讀取字符,但是當我在 main 外部聲明變量時收到分段錯誤。 如果我刪除它們並嘗試從文件中讀取,一切都會順利進行。 我正在使用 dev c++ 5.7.1 和 mingw 4.8.1 便攜版。
我已將問題隔離為僅聲明了一些變量和文件讀取代碼。 這段代碼來自我正在嘗試開發的一個更大的應用程序(我正在自學游戲開發)。
#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;
}
我得到 output: 1,文件已打開。 但是沒有從文件中讀取字符。 調試信息
為什么會這樣?
根據您對我的評論的回答,聲明bool read
覆蓋read
fread
使用的 function 。 重命名它或將其移動到另一個命名空間或 class。
我的編譯器都不能重現同樣的問題。 這是非常奇怪的行為,因為至少“讀取”的聲明應該與正確覆蓋的原始聲明相同。 也許您的stdlib以不同的方式調用 read 。
歡迎來到 StackOverflow...
首先,就像說你的編譯器很舊。 版本 4.8.1,而當前 G++ 是版本 9.2。
盡量避免使用全局變量。 這是允許的,但不是很好的封裝設計。 它們不存儲在堆棧或普通堆中,而是存儲在 memory 的某個不起眼的部分中。
無論如何,你沒有分享 test.txt,所以我自己制作了包含
acb
並清理了你的代碼
#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;
}
而我的 output 是
1
abc
即使您的原始代碼讀取到文件末尾,我真的希望至少有一些 output。 編譯器一直在更新。 也許您實際上遇到了一個舊錯誤...您真的應該更新
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.