简体   繁体   English

仅当文件存在时才使用 fstream 读取/写入文件

[英]Read/write file only if it exists using fstream

I'm handling a file using fstream, and I need to read and write to it.我正在使用 fstream 处理一个文件,我需要读取和写入它。 However, even using std::ios:in, the file continues to be created if it does not exist:但是,即使使用 std::ios:in,如果文件不存在,它也会继续创建:

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

Any thoughts?有什么想法吗?

Thanks in advance!提前致谢!

There are different approaches, you can do it the old way有不同的方法,你可以用旧的方法来做

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

Or you can use standard library std::filesystem::exists introduced in C++17.或者您可以使用 C++17 中引入的标准库std::filesystem::exists Read more about it .阅读更多相关信息

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

Remember that file can exist but you can fail to interact with it (read/write from/to it).请记住,文件可以存在,但您可能无法与它交互(从读取/写入/向它写入)。

If needed:如果需要的话:

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

Read documentation carefully:仔细阅读文档:

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

The file is opened as if by calling std::fopen with the second argument ( mode ) determined as follows:该文件的打开方式如同通过调用std::fopen并使用第二个参数 ( mode ) 确定,如下所示:

mode模式 openmode & ~ate openmode & ~ate Action if file already exists文件已存在时的操作 Action if file does not exist文件不存在时的动作
"r" “r” in Read from start从头开始阅读 Failure to open打不开
"w" “w” out, out|trunc出,出|截断 Destroy contents销毁内容 Create new创建新的
"a" “一种” app, out|app应用程序,输出|应用程序 Append to file附加到文件 Create new创建新的
"r+" “r+” out|in出|入 Read from start从头开始阅读 Error错误
"w+" “w+” out|in|trunc出|入|截断 Destroy contents销毁内容 Create new创建新的
"a+" “一个+” out|in|app, in|app出|进|应用,进|应用 Write to end写到最后 Create new创建新的
"rb" “rb” binary|in二进制|输入 Read from start从头开始阅读 Failure to open打不开
"wb" “wb” binary|out, binary|out|trunc二进制|输出,二进制|输出|截断 Destroy contents销毁内容 Create new创建新的
"ab" “ab” binary|app, binary|out|app二进制|应用程序,二进制|输出|应用程序 Write to end写到最后 Create new创建新的
"r+b" “R+B” binary|out|in二进制|输出|输入 Read from start从头开始阅读 Error错误
"w+b" “w+b” binary|out|in|trunc二进制|输出|输入|截断 Destroy contents销毁内容 Create new创建新的
"a+b" “a+b” binary|out|in|app, binary|in|app二进制|输出|输入|应用,二进制|输入|应用 Write to end写到最后 Create new创建新的

This should explain everything.这应该可以解释一切。

Just drop app flag and you done.只需放下app标志即可完成。

https://wandbox.org/permlink/p4vLC8ane9Ndh1gN https://wandbox.org/permlink/p4vLC8ane9Ndh1gN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM