简体   繁体   中英

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. However, even using std::ios:in, the file continues to be created if it does not exist:

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. 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

The file is opened as if by calling std::fopen with the second argument ( mode ) determined as follows:

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

This should explain everything.

Just drop app flag and you done.

https://wandbox.org/permlink/p4vLC8ane9Ndh1gN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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