Skip to content

Conversation

foryoung365
Copy link

std::fstream fs(simplePath, std::ios::app);

File existence check using fstream with ios::app is implemented as a workaround because:

  • ifstream::good() incorrectly handles directories on Unix-like systems
  • <sys/stat.h> adds platform-specific dependencies
  • It avoids duplication with CppCheck's 'path' implementation
  • std::filesystem (the proper solution) requires C++17 support

simplecpp.cpp Outdated

// This is a workaround to properly check if a file exists,
// since std::ifstream::good() incorrectly returns true for directories
std::fstream fs(simplePath, std::ios::app);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That is an interesting handling.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This solution still has flaws; when the file does not exist, an empty file will be created. Therefore, I replaced it with

std::fstream fs(simplePath, std::ios::in|std::ios::out);

Here is a simple test result (linux, mac, and windows):
https://github.com/foryoung365/CppFstreamTest/actions/runs/11549258974

Here are some references:
https://en.cppreference.com/w/cpp/io/basic_filebuf/open

Copy link
Collaborator

@firewave firewave Sep 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI I used this in #435 to improve the checks in the CLI.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That check is also flawed because it will fail if the files are read-only.

@firewave
Copy link
Collaborator

Thanks. Please give me a few days since I might be out sick.

@danmar
Copy link
Owner

danmar commented Dec 5, 2024

how do we test this? you can easily check if a file exists or not in a unit test but if you need to test various edge cases I guess a pytest working in a tempdir is better.

@firewave
Copy link
Collaborator

The issue referenced here was fixed in #443. So I think this can be closed.

And #339 contains improved code for checking for the existence of a file/directory.

I also filed https://trac.cppcheck.net/ticket/14133 about detecting such code with Cppcheck.

@firewave firewave closed this Sep 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants