在文件中写入后立即从文件中读取

Reading from file right after Writing in it

本文关键字:文件 读取      更新时间:2023-10-16

我想写入文件然后从中读取并打印结果

我的代码

#include<iostream>
#include<fstream>
using namespace std;
int main(int argc,char* argv[]){
int x,y;
ofstream fd1(argv[1]);
ifstream fd2(argv[1]);
cin>>x;
fd1<<x;
fd2>>y;
cout<<"just read "<<y<<endl;
fd1.close();
fd2.close();
return 0;
}

怎么了?我输入123,它输出"just read -1078463800"

即使你可以同时打开read &写,这个写操作是缓冲的,这意味着它可能不会被写入磁盘,除非您刷新流(或关闭文件)。

当然,下面的代码可以完美地工作:

#include<iostream>
#include<fstream>
using namespace std;
int main(int argc,char* argv[]){
int x,y;
ofstream fd1(argv[1]);
cin>>x;
fd1<<x;

fd1.close();
ifstream fd2(argv[1]);
if (fd2.good())
{
   cout << "read OK" << endl;
}
fd2>>y;
cout<<"just read "<<y<<endl;
fd2.close();
return 0;
}

fd2>>y语句失败,因为还没有从文件中读取任何内容。std::ofstream缓冲其输出,并且在尝试从文件中读取之前,您没有将缓冲区刷新到磁盘上的文件。

std::ofstream在以下情况下刷新缓冲区:

  1. 写入新行

  2. 它的flush()方法被直接调用,或者当std::flushstd::endl流到它时。

试试这个:

fd1 << x << flush;

或:

fd1 << x;
fd1.flush();

顺便说一句,您确实应该在此过程中检查错误。std::ofstreamstd::ifstream构造函数可能无法创建/打开文件。<<>>操作符可能无法写入/读取值。所有这些操作都可以报告您可以检查的错误。例如:

#include <iostream>
#include <fstream>
int main(int argc, char* argv[])
{
    int x, y;
    std::ofstream fd1(argv[1]);
    std::ifstream fd2(argv[1]);
    if (!fd1.is_open())
    {
        std::cout << "cannot create output file" << std::endl;
    }
    else if (!fd2.is_open())
    {
        std::cout << "cannot open input file" << std::endl;
    }
    else if (!(std::cin >> x))
    {
        std::cout << "invalid input" << std::endl;
    }
    else if (!(fd1 << x << std::flush))
    {
        std::cout << "cannot write to output file" << std::endl;
    }
    else if (!(fd2 >> y))
    {
        std::cout << "cannot read from input file" << std::endl;
    }
    else
    {
        std::cout << "just read " << y << std::endl;
    }
    return 0;
}

另外:

#include <iostream>
#include <fstream>
int main(int argc, char* argv[])
{
    int x, y;
    std::ofstream fd1;
    std::ifstream fd2;
    fd1.exceptions(std::ofstream::failbit);
    fd2.exceptions(std::ifstream::failbit);
    std::cin.exceptions(std::ifstream::failbit);
    try
    {
        fd1.open(argv[1]);
        fd2.open(argv[1]);
        std::cin >> x;
        fd1 << x << std::flush;
        fd2 >> y;
        std::cout << "just read " << y << std::endl;
    }
    catch (const std::ios_base::failure &e)
    {
        std::cout << "error! " << e.what() << std::endl;
    }
    return 0;
}