写入后立即从文件中读取

时间:2016-11-09 20:08:15

标签: c++ fstream ifstream ofstream

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

这是我的代码

#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输出“只读-1078463800”

2 个答案:

答案 0 :(得分:2)

即使您可以在阅读和阅读中打开两者写,这个写操作是缓冲,这意味着它可能不会被写入磁盘,除非你刷新流(或你关闭文件)。

当然,下面的代码完美无缺:

#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;
}

答案 1 :(得分:2)

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

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

  1. 写了一个新行。

  2. 直接或在flush()std::flush()流式传输时调用std::endl方法。

  3. 试试这个:

    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;
    }
    
相关问题