0

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!

3
  • if (std::filesystem::exists("myfile.txt")) ... Commented Jun 24, 2021 at 14:37
  • since removing app fixes issue vote to close as typo. Commented Jun 24, 2021 at 15:14
  • @MarekR i agree Commented Jun 24, 2021 at 15:16

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

The first method is not effective as fstream creates the file if it doesn't exist. About the second method, I can't use c++ 17 due to some limitations. I thought the std::ios::in flag would be enough to only handle the file if it already exists. Is there another way to do this?
maybe open using r+ mode? look at @Marek R answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.