注册 登录
编程论坛 C++教室

读取文件后数据丢失

ke_liu 发布于 2020-05-10 21:15, 2548 次点击

程序代码:

#include<fstream>
#include<iostream>
using namespace std;
int main()
{
    fstream file("E:\\MyCppSource\\习题13-4\\Debug\\f1.dat", ios::in | ios::out);
    int num[5],i;
    if (!file) exit(1);
    for (i = 0; i < 5; i++)
    {
        cin >> num[i];//从键盘得到整数
        file << num[i] << ' ';//将他输出到f1.dat文件
        file >> num[i];//从f1.dat文件读入整数
        cout << num[i] << ' ';//将他们输出到显示器
    }
    return 0;
}

假如我输入1 3 5 7 9输出到f1.dat文件,在读取出来输出就这样了:0 3 5 7 9,谁能解释一下吗,是什么问题?小白求教
运行结果:
只有本站会员才能查看附件,请 登录
6 回复
#2
fulltimelink2020-05-11 13:06
写入后flush一下,再读
程序代码:

        cin >> num[i];//从键盘得到整数
        file << num[i] << ' ';//将他输出到f1.dat文件
        file.flush();
        file >> num[i];//从f1.dat文件读入整数
        cout << num[i] << ' ';//将他们输出到显示器
#3
rjsp2020-05-11 15:24
回复 楼主 ke_liu
最好不这么做,
理论上读写之间有 seek、flush、sync 等之一就行了,实际上还是有各种不兼容

程序代码:
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
    fstream file( "f1.dat", ios::in|ios::out );
    if( !file )
    {
        cerr << "打开文件失败\n";
        return 1;
    }

    for( size_t i=0; i!=5; ++i )
    {
        int value;
        if( !(cin>>value) )
        {
            cerr << "键盘输入失败\n";
            return 2;
        }

        streampos pos1 = file.tellp();
        if( !(file<<value<<' ') )
        {
            cerr << "写入文件失败\n";
            return 3;
        }
        streampos pos2 = file.tellp();

        file.seekg( pos1 );
        if( !(file>>value) )
        {
            cerr << "读取文件失败\n";
            return 4;
        }
        file.seekp( pos2 );

        cout << value << ' ';
    }
    return 0;
}

#4
ke_liu2020-05-11 18:52
回复 2楼 fulltimelink
flush函数的作用我不明白,搜了下看不懂,我想问下我的这个代码是如何运行的,为什么前面的数字就莫名其妙没有了呢?
#5
ke_liu2020-05-11 18:58
回复 3楼 rjsp
你说的那些函数我都不知道,我想知道我的那个代码为什么就不能得到想要的结果,它是如何运行的?
#6
fulltimelink2020-05-12 09:31
这个看编译器的,你可以debug下
只有本站会员才能查看附件,请 登录

在Clion下可能就不会出现
只有本站会员才能查看附件,请 登录

不知道你有没有留意,文件最终只写入了1,而并不是9
#7
ke_liu2020-05-13 10:14
回复 6楼 fulltimelink
好的,谢谢!
1