gpt4 book ai didi

c++ - 程序写得很好,但不能读

转载 作者:行者123 更新时间:2023-11-30 02:30:34 27 4
gpt4 key购买 nike

#include<fstream>
#include<iostream>
using namespace std;
int main()
{
int i = 20;

fstream fs("someFile.dat", ios::out | ios::binary | ios::in);
if(!fs)
{
cout << "FILE COULD NOT BE OPENED" << endl;
}

fs.write(reinterpret_cast<const char*>(&i),sizeof(int));
i = 0;
fs.read(reinterpret_cast<char*>(&i),sizeof(int));
cout << i << endl; // shows 0
}

最后 cout 中的 'i' 应该显示 20 但它显示为 0。

最佳答案

写入文件后,您位于文件末尾。

您可以使用 tellg 来解决这个问题,或“告诉得到”:

std::cout << "Position in file is: " << fs.tellg() << std::endl;

这将告诉您从文件开头开始在文件中的字节偏移量。您需要先在文件中寻找合适的位置,然后才能从文件中读取字节。为此,我们可以使用 seekg , 或“寻找得到”。

fs.seekg(0);

这会查找文件的开头(从文件开头开始的字节偏移量为 0),因此您应该能够正确地从文件中读取。

对于您的示例,seekgseekp 应该相同,tellgtellp 也是相同的,但是您理想情况下,应该将以“g”(表示“get”)结尾的成员函数用于输入流,将以“p”(表示“put”)结尾的函数用于输出流。

编辑

@Borgleader 在评论中提出了一个很好的观点,对于更复杂的示例,您可能不知道读取是否失败。为此,您可以检查失败位:

if (fs.fail()) {   
// you can check more specific error codes with std::ios_base::iostate
// fs.fail() will evaluate to 0 if no error, or false, otherwise it has an error
std::cout << "Failed to read from file" << std::endl;
}

更新

要分析 iostate 标志,可以使用 fstream 成员函数 goodeoffailbad .下面是一个检查原始示例的 fstream 的 iostate 的快速示例:

#include <fstream>
#include <iostream>

int main()
{
int i = 20;
std::fstream fs("someFile.dat", std::ios::out | std::ios::binary | std::ios::in);
fs.write(reinterpret_cast<const char*>(&i), sizeof(int));
i = 0;
fs.read(reinterpret_cast<char*>(&i), sizeof(int));
// you can check other settings via the ios::fail() member function
if (fs.good()) { // checks goodbit
std::cout << "File is normal, no errors\n";
}
if (fs.eof()) { // checks end of file
std::cout << "End of file\n";
}
if (fs.fail()) { // checks failbit or badbit
std::cout << "Failed to read, failbit\n";
}
if (fs.bad()) { // checks the badbit
std::cout << "Failed to read, badbit\n";
}
}

这在运行时产生以下输出:

End of file
Failed to read, failbit

总的来说,经常检查读取是否失败就足够了,除非你需要进一步完善你的逻辑。

关于c++ - 程序写得很好,但不能读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38422995/

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