从turbo c++中的二进制文件读取后出现意外输出

Unexpected output after reading from a binary file in turbo c++

本文关键字:意外 输出 读取 二进制文件 turbo c++      更新时间:2023-10-16

在读取文件时写入文件后,会得到意外的输出
我写的代码是:

#include<fstream.h>
#include<conio.h>
#include<string.h>
struct test
{
    char que[100];
    char ans[20];
};
int main()
{
    test s, d;
    clrscr();
    ofstream out("test.dat", ios::binary | ios::app);
    ifstream in("test.dat", ios::binary | ios::in);
    strcpy(s.que, "2.How many ways the letters of the word abas be arranged to  form words with or without meaning");
    strcpy(s.ans, "180");
    out.write((char*) &s, sizeof(test));
    while(!in.eof())
    {
        in.getline((char*) &d, sizeof(test));
        cout << d.que << 'n' << d.ans;
    }
    getch();
    return 0;
}

我得到的输出是:

2.How many ways the letters of the word abas be arranged to form words with or w
ithout meaning
180
180

这是我处理的输出,中间有一些任意字符。

我做错了什么?为什么我存储在s.ans中的字符串也被写入s.que

我通过以下更改实现了这一点:

  1. 在写入文件后添加out.close()以刷新输出缓冲区
  2. getline替换为read,以便在write写入字节时检索这些字节。CCD_ 7可能在某些条件下给出不同的结果
  3. 将已读语句移动到while条件:

    while(in.read((char *) &d, sizeof(test)))

由于循环主体中的read语句in.eof()不会在读取最后一个test对象后立即返回true,因此循环将最后执行一次。