提问者:小点点

C++文件读取错误


于是,我运行了这个程序,结果我预期的答案是26,结果却得到了-52。 请解释代码读取字符不正确的原因。

char x = 26;
ofstream ofile("file.txt");
ofile << x;
ifstream ifile("file.txt");
char y;
ifile >> y;
cout << (int)y;

共3个答案

匿名用户

如果要写入非文本数据,则应以二进制模式打开文件:

ofstream ofile("file.txt", ios_base::binary);

一个好的做法是检查文件是否实际打开成功:

ofstream ofile("file.txt", ios_base::binary);
if (!ofile) return -1;

在关闭文件之前,缓冲区很有可能不会被刷新,因此在关闭文件之前读取另一个流中的文件是没有意义的:

ofile << x;
ofile.close();

一个好主意是用endl完成对cout的输出:

cout << (int) y << endl;

所以你需要这样的东西:

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    char x = 26;

    ofstream ofile("file.txt", ios_base::binary);
    if (!ofile) return -1;
    ofile << x;
    ofile.close();

    ifstream ifile("file.txt", ios_base::binary);
    if (!ifile) return -1;
    char y;
    ifile >> y;
    cout << (int) y << endl;
    ifile.close();

    return 0;
}

匿名用户

当您写入ofstream时,您所写入的数据不会直接写入文件,而是保存在内存缓冲区中,只有当缓冲区已满,查找流,刷新流或关闭流时,才会将缓冲区写入文件。

还要注意,如果您不是在编写纯文本,那么以二进制模式打开文件会更安全,以确保您读/写的数据是准确的。 您还应该使用readwrite,而不是格式化的I/O函数(或者对于单个字符使用getput)。

增加一些错误检查也是一个好主意。

char x = 26;
ofstream ofile("file.txt", std::ios_base::binary);
ofile.put(x);
if (!ofile)
{
  std::cout << "write failed\n";
  return;
}
ofile.close();
ifstream ifile("file.txt", std::ios_base::binary);
char y;
ifile.get(y);
if (!ifile)
{
  std::cout << "read failed\n";
  return;
}
cout << (int)y << "\n";

在Windows上测试后,需要做的两个更改是

  1. 以二进制模式打开ifile
  2. 在打开iflie
  3. 之前关闭/刷新ofile

匿名用户

这就是你想要的。

    char x = 26;
    ofstream ofile("file.txt");
    ofile << x;
    ofile.close ();       // <- closing the file
    ifstream ifile("file.txt");
    char y;
    ifile >> y;
    cout << "Value: " << (int)y << endl;
    return 0;

在这种情况下,您可能正在读取尚未写入磁盘的内容(由于缓冲)

输出:

manuel@desktop:~/projects$ g++ -Wall -Wextra -g main.cc -o main -Wpedantic && ./main
Value: 26
manuel@desktop:~/projects$ hexdump file.txt 
0000000 001a                                   
0000001

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|文件|读取)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?