使用 fstream 创建文件,如果它不存在使用 seekp/seekg?


fstream file(file_1.c_str(), ios::out | ios::in | ios::ate); //convert string to const char*

如果文件不存在则错误。if ( ! file ) = true

fstream file(file_1.c_str(), ios::out | ios::in | ios::app); //convert string to const char*

使用ios::app seekg &seekp功能不工作。file.seekg(4, ios_base::beg);

我想要:

  1. 用户输入文件名
  2. 如果不存在则创建文件
  3. 使用seekg &seekp;
  4. 如果你再次运行程序,不删除文件。

如果我理解正确的话,你需要这样的东西:

#include <iostream>
#include <fstream>
#include <string>
int main()
{
    string name;
    std::cin>>name;
    std::ofstream file (name.c_str());
    outfile << "Text in file." << std::endl;
    file.close();
    return 0;
}

最新更新