【问题标题】:Create file using fstream if it doesn't exist that utilizes seekp/seekg?如果不存在使用 seekp/seekg 的文件,则使用 fstream 创建文件?
【发布时间】:2023-03-18 17:54:01
【问题描述】:
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 seekgseekp 功能不起作用。 file.seekg(4, ios_base::beg);

我想要:

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

【问题讨论】:

  • 如果文件不存在,搜索与打开文件有什么关系?有什么问题?

标签: c++ fstream seekg


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 2012-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多