Fstream打开文件在std :: fstream :: in | std :: fstream :: out | std :: fstream :: app模式 [英] Fstream open file in std::fstream::in | std::fstream::out | std::fstream::app mode

查看:1532
本文介绍了Fstream打开文件在std :: fstream :: in | std :: fstream :: out | std :: fstream :: app模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要能够创建一个不存在的文件。设计如下:
我有一个线程为所有文件IO,并在封装的文件的数据结构,我有一个std :: fstream file_handle。

I need to be able to create a non-existent file. The design is as follows : I have 1 thread for all file IO, and in the data structure that encapsulates the file, I have a std::fstream file_handle.

我可以在模式 - std :: fstream :: in |中创建和打开此文件std :: fstream :: out | std :: fstream :: app
我需要这个,因为我必须使用这个句柄来做这两个 - 读,并写入文件的结尾。

Can I create and open this file in the mode - std::fstream::in | std::fstream::out | std::fstream::app ? I need this because I have to use this one handle to do both - reads, and writes to the end of the file.

但是这不是创建文件。这是我有的:

However this is not creating the file. Here's what I have :

class file_io
{
   std::string filename;
   std::fstream file_handle;
   file_io(std::string name)
   {
      filename = name;
   }
   void open_file()
   {
      if(!file_handle.is_open())
      {
          file_handle.open(filename.c_str(), std::fstream::in | std::fstream::out | std::fstream::app);
          if(!file_handle.is_open())
          {
              std::cout << "Could not open file " << filename ;
          }
          else
          {
              std::cout << "successfully opened file " << filename;
          }
      }
   }
   ~file_io()
   {
      if(file_handle.is_open)
      file_handle.close();
   }
};

每次我需要写入文件结尾或读取文件内容时调用open_file 。
但是文件不会被创建。任何人都可以帮助我明白我在这里做错了什么正确的方法是解决我的问题?

I call onto open_file each time I need to write into end of the file, or read the file contents. But the file does not get created. Can anyone please help me understand what I am doing wrong here, and what the right approach is to solve my problem?

此外,如果唯一的选择是有不同的文件句柄,一个用于append(需要在这里创建),一个用于读取,是否可以如果我读取文件,而append的文件句柄仍然打开?

Also, if the only alternative is to have to different file handles, one for append(need to create here as well) and one for reads, is it okay if I read the file while the file handle for append is still open? Also, what should the mode of opening be for create if non-existent and append ?

推荐答案

因此,阅读std上的文档: :stream打开方法它看起来像打开将失败,当在打开中指定'in'和'app'。

So reading the docs on std::stream open method it looks like the open will fail when both 'in' and 'app' are specified in the open. Try leaving the 'in' off and see what happens.

如果模式同时包含trunc和app设置,则打开操作失败,如果设置了两者之一,也会失败但不是,或者如果同时设置了app和in。

"If the mode has both trunc and app set, the opening operation fails. It also fails if either is set but out is not, or if both app and in are set."

std :: fstream reference

这篇关于Fstream打开文件在std :: fstream :: in | std :: fstream :: out | std :: fstream :: app模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆