【问题标题】:Opening a file to read and write, create it if it doesn't exist打开一个文件进行读写,如果它不存在则创建它
【发布时间】:2021-04-15 08:39:44
【问题描述】:

我试图在读写模式下创建一个文件,但它没有创建文件,可能是什么问题?

这是代码:

fstream file("NameFile.txt", ios::out| ios::in);

程序将启动,但不会创建任何文件。

【问题讨论】:

  • 这能回答你的问题吗? std::fstream doesn't create file
  • 这样它甚至不会创建任何东西。 fstream file;file.open("test.txt",ios::out | ios::in)

标签: c++ file


【解决方案1】:

当你使用fstream打开文件时:

  • 要读取,文件必须存在;

  • 要写入,您需要指定写入模式,ofstream 会为您执行此操作,但使用 fstream 您需要自己执行:


在你写的时候替换文件的内容(ofstream默认模式)。

  std::fstream file("NameFile.txt", std::ios::out | std::ios::in | std::ios::trunc);
                                                                   ^^^^^^^^^^^^^^^

写入时附加到文件中的现有数据。

  std::fstream file("NameFile.txt", std::ios::out | std::ios::in | std::ios::app);
                                                                   ^^^^^^^^^^^^^

请注意,读取或写入后,您需要在文件中设置偏移位置,例如:

std::string s = "my string";
std::string in;

file << s; 
file >> in;

file &gt;&gt; in不会读取任何内容,位置指示器在文件末尾file &lt;&lt; s之后,如果要读取之前写入的数据,则需要重新设置,例如:

file << s; 
file.seekg(0);
file >> in;

这会将读取位置指示器重置为文件的开头,在读取文件之前,请在此处了解更多信息:

https://en.cppreference.com/w/cpp/io/basic_fstream

【讨论】:

    【解决方案2】:

    好吧,你初始化了一个对象,现在来创建一个文件使用

    file.open();
    

    fstream won't create a file

    【讨论】:

    • 构造函数应该创建文件。无需open
    • 这样它甚至不会创建任何东西。 fstream file;file.open("test.txt",ios::out | ios::in)
    猜你喜欢
    • 2021-01-31
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2014-07-20
    • 2020-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多