gpt4 book ai didi

c++ - fstream,先写,再读,再写,最后一次写失败,不知道是什么原因

转载 作者:行者123 更新时间:2023-11-30 05:08:28 26 4
gpt4 key购买 nike

fstream fs("f.txt", fstream::in | fstream::out | fstream::trunc);
if(fs)
{
string str = "45464748";
fs << str;

fs.seekg(0, ios::beg);

int i = -1;
fs >> i;
cout << i << endl;

fs.seekp(0, ios::beg);

i = 0x41424344;
fs << i;

fs.close();
}

f.txt内容是“45464748”,但我应该理解它的内容是“1094861636”。我不知道原因,请帮助我。

最佳答案

流状态的 eof 位由之前的读取设置,因此写入无效。写入前清除流状态。

void ftest()
{
std::fstream fs("f.txt", std::fstream::in | std::fstream::out | std::fstream::trunc);
if(fs)
{
std::cout << "A: " << (fs.eof() ? "eof" : "neof") << std::endl;
std::string str = "45464748";
fs << str;
std::cout << "B: " << (fs.eof() ? "eof" : "neof") << std::endl;
fs.seekg(0, std::ios::beg);
std::cout << "C: " << (fs.eof() ? "eof" : "neof") << std::endl;
int i = -1;

// THIS read sets the EOF bit.
fs >> i;

std::cout << "D: " << (fs.eof() ? "eof" : "neof") << std::endl;
std::cout << i << std::endl;
fs.seekp(0, std::ios::beg);
std::cout << "E: " << (fs.eof() ? "eof" : "neof") << std::endl;
i = 0x41424344;
std::cout << "F: " << (fs.eof() ? "eof" : "neof") << std::endl;
fs << "not written";
fs.clear ();
std::cout << "G: " << (fs.eof() ? "eof" : "neof") << std::endl;
fs << i;
fs.close();
}
}

输出:

A: neof
B: neof
C: neof
D: eof
45464748
E: eof
F: eof
G: neof

文件内容:

1094861636

关于c++ - fstream,先写,再读,再写,最后一次写失败,不知道是什么原因,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46824238/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com