【问题标题】:Read/write file only if it exists using fstream仅当文件存在时使用 fstream 读取/写入文件
【发布时间】:2021-06-24 14:36:30
【问题描述】:

我正在使用 fstream 处理一个文件,我需要对其进行读写。但是,即使使用 std::ios:in,如果文件不存在,也会继续创建:

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

有什么想法吗?

提前致谢!

【问题讨论】:

  • if (std::filesystem::exists("myfile.txt")) ...
  • 因为删除 app 修复了问题投票以作为拼写错误关闭。
  • @MarekR 我同意

标签: c++ file


【解决方案1】:

仔细阅读文档:

std::basic_filebuf<CharT,Traits>::open - cppreference.com

文件打开就像调用std::fopen,第二个参数(mode)确定如下:

mode openmode & ~ate Action if file already exists Action if file does not exist
"r" in Read from start Failure to open
"w" out, out|trunc Destroy contents Create new
"a" app, out|app Append to file Create new
"r+" out|in Read from start Error
"w+" out|in|trunc Destroy contents Create new
"a+" out|in|app, in|app Write to end Create new
"rb" binary|in Read from start Failure to open
"wb" binary|out, binary|out|trunc Destroy contents Create new
"ab" binary|app, binary|out|app Write to end Create new
"r+b" binary|out|in Read from start Error
"w+b" binary|out|in|trunc Destroy contents Create new
"a+b" binary|out|in|app, binary|in|app Write to end Create new

这应该可以解释一切。

只需放下app 标志即可。

https://wandbox.org/permlink/p4vLC8ane9Ndh1gN

【讨论】:

    【解决方案2】:

    有不同的方法,你可以用旧方法来做

    std::fstream file("myfile.txt", std::ios::in | std::ios::out); // edited after comment
    if (!file)
    {
        // Can't open file for some reason
    }
    

    或者您可以使用 C++17 中引入的标准库std::filesystem::existsRead more about it.

    if (std::filesystem::exists("myfile.txt")) { // Exists }
    

    请记住,文件可以存在,但您可能无法与之交互(读取/写入/写入)。

    如果需要:

    g++ -std=c++17 yourFile.cpp -o output_executable_name
    

    【讨论】:

    • 第一种方法无效,如果文件不存在,fstream 会创建该文件。关于第二种方法,由于某些限制,我不能使用 c++ 17。我认为 std::ios::in 标志足以仅处理已存在的文件。还有其他方法吗?
    • 可能使用 r+ 模式打开?看看@Marek R 的回答
    猜你喜欢
    • 2015-12-02
    • 1970-01-01
    • 2021-03-23
    • 2012-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    相关资源
    最近更新 更多