gpt4 book ai didi

以读写模式打开文件时的c++文件流问题

转载 作者:行者123 更新时间:2023-11-28 01:36:34 24 4
gpt4 key购买 nike

考虑以下代码片段:

const char * filePath = "C:/blah.mtt";
fstream fs(filePath, ios::in | ios::out | ios::binary);
if (fs.fail())
std::cout << "Failed to open the file!\n";

fs.fail() 检查总是成功的。这是否意味着我不能同时以读写模式打开文件?

首先创建一个空文件,然后运行上面的代码,fs.fail() 始终为 false。 fstream 类的这种行为的合理性是什么?

注意:我确实拥有创建该文件的必要权限。我正在使用 VS2015 在 Windows 10 上尝试这个

最佳答案

Does it mean that I can't open a file in both read write mode at the same time?

不,您可以这样做,但问题是您是否可以通过这样做创建一个文件。

通常您需要添加 trunc 标志(具有讽刺意味的是如何处理现有文件的选项之一),或删除 in 标志(参见 here ).

是的,这有点痛苦,但它来自原始 POSIX API 的工作方式。怪他们!

Creating an empty file first and then running the above code, fs.fail() is false always. What is the rational for such a behavior by the fstream class?

您始终可以打开一个存在的文件(嗯,受权限限制)。这种行为是有道理的。

关于以读写模式打开文件时的c++文件流问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49027307/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com