0

How to see if a user already has a file? For example, I want this to make a text file and if a user already has a file in their system for it not to work and send an error.

#include <iostream>
#include <fstream>
using namespace std;

int main() {
    int number;
    cout << "This is just a test. Insert the number 10 to make it work" << endl;
    cin >> number;
    if (number == 10) {
        ofstream read("read.txt");
    }
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 3
    Probably using [https://en.cppreference.com/w/cpp/filesystem/exists](https://en.cppreference.com/w/cpp/filesystem/exists) if you have a compiler with support for c++17 the 2017 standard. – drescherjm Feb 16 '21 at 16:02
  • you want to know if a file with a given name already exists? – 463035818_is_not_an_ai Feb 16 '21 at 16:02
  • largest_prime_is_463035818 yes – GoatBucker Feb 16 '21 at 16:14
  • @user1810087 what does that mean – GoatBucker Feb 16 '21 at 16:16
  • 1
    @GoatBucker There is no way to check for file non-existence using `ofstream`, as it will create a new file if one does not exist yet. `ifstream`, on the other hand, can detect a file's non-existence without creating a new file, if you open the file in read-only mode. But a file could fail to open for many reasons (non-existence, access denied, etc), and `ifstream` can't tell you WHY it failed, you would have to get that info from the OS directly (`GetLastError()`, `errno`, etc) – Remy Lebeau Feb 16 '21 at 18:08
  • @RemyLebeau _"There is no way to check for file non-existence using `ofstream`, as it will create a new file if one does not exist yet"_ - In C++23, `ofstream` will finally have an option to open in exclusive mode just like `std::fopen` has been able to do since C++17. I moved my answer to the [duplicate](https://stackoverflow.com/questions/16141018/how-to-open-file-in-exclusive-mode-in-c). – Ted Lyngmo Jan 05 '23 at 11:04

1 Answers1

3

If your goal is to check if a file exists at a given location, and if your working with C++17 or higher, you can use std::filesystem::exists.

if (std::filesystem::exists("read.txt")) { ... }
D-RAJ
  • 3,263
  • 2
  • 6
  • 24
  • 2
    Library support for std::filesystem is still lagging :(. But yes, if your implementation supports it, this is the way to go. – spectras Feb 16 '21 at 16:13
  • 2
    @spectras Only if you're Apple. Every other major compiler supports this. Apple's C++ compiler is so far behind it isn't funny. They've basically abandoned it for Swift. – Casey Feb 16 '21 at 16:16