0

I've been writing a code using fstream to create a file having a specific number, now I want mmy program to check whenever a new entry is being made if the name of that entry has already been used or not, TIA for all your help. I've tried doing it myself as in the code attached, but I'm not sure if it's working properly. The aim is to check if the file has already been made if so and error would be given otherwise the user would be prompted to continue on making the new file.

cout<<"Enter your NIC or Form B number: ";
cin.ignore();
gets(det.nic);

entries.open(det.nic, ios::out);
if (!entries)
{
    cout<<setw(70)<<"\nYou've already availed the fund!\n";
    system("pause");
    system("cls");
    goto m;
}
else
{
mch
  • 9,424
  • 2
  • 28
  • 42

2 Answers2

1

If you only need to check if a file exists without actually using it, you can use the <filesystem> library if your compiler supports it. It provides an exists() function that will do that without opening the file.

#include <filesystem>

namespace fs = std::filesystem;

if (fs::exists(file_path)) {
    std::cout << "File already exists!\n";
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
Kaldrr
  • 2,780
  • 8
  • 11
  • Isn't there any other way because I'm aiming to use to libraries that any user having codeblocks would be able to use, it's more of an assignment – Syed Uzair Iftikhar May 28 '20 at 07:38
  • @SyedUzairIftikhar `filesystem` library is part of C++ standard since C++17, with a modern compiler and appropriate flags used during compilation it should work without using any 3rd party libraries. – Kaldrr May 28 '20 at 07:46
0

You can use std::ifstream("filename").good().

Bonus tip: Regarding your description of a problem (create a file it does not exist), haev a look about race conditions.

olepinto
  • 351
  • 3
  • 8