发布
社区首页 >问答首页 >从刚刚由std::ofstream创建和编写的文件中读取文件时是否存在任何问题?

从刚刚由std::ofstream创建和编写的文件中读取文件时是否存在任何问题?
EN

Stack Overflow用户
提问于 2022-08-25 07:46:50
回答 1查看 52关注 0票数 0

对于下面的代码片段,当std::fstream被销毁时,文件是否保证在\之后写入磁盘?

代码语言:javascript
代码运行次数:0
复制
//the writer
#include<iostream>
#include<fstream>
#include<chrono>
#include<thread>
using namespace std;
int main(int argc,char* argv[]){
    
    {
        std::ofstream file_writer{"test.txt"};

        file_writer << "when the file is actually written out?" << std::endl;
    }


    std::this_thread::sleep_for(std::chrono::seconds(3600));  //the reader below would be called and this process is still alive.  
    return 0;
}

保证首先调用代码段。

由于操作系统可能会推迟实际操作(这是C++无法控制的),现在可能在磁盘上没有实际文件。我不确定是否存在潜在的问题,如果我调用下面的代码片段来读取由第一个代码片段销毁后创建和编写的文件,那么file_writer就会被销毁。

代码语言:javascript
代码运行次数:0
复制
//the reader
#include<iostream>
#include<fstream>
using namespace std;
int main(int argc,char* argv[]){
    
    {
        std::ifstream file_reader{"test.txt"};

        file_reader.read();
    }
    
    return 0;
}
EN

回答 1

Stack Overflow用户

发布于 2022-08-25 07:52:03

您可以使用输出流创建文件,该文件通常是同步的。

然后,将输出流写到文件,这通常是通过页面缓存进行的。

因此,在运行第一个程序之后,该文件就可以读取数据和存在性了。

问题更深一点,因为您假设程序的运行顺序,在100%的情况下,这要求您在外部同步(通过PID文件或信号量)。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73483711

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档