0
[c++] How to check if a file exists or not in c++?
I basically am trying to see if a file exists. If it exists output a error saying "the file already exists. do you want to overwrite it?". If it doesn't, then make it. The code I found makes the file automatically but if the file already exists, it overwrites the whole data. The only solution I've found is using boost. Is there any non-boost way to do this? please and thanks, y'all! :)
6 Réponses
+ 5
#include <iostream>
#include <fstream>
using namespace std;
int main() {
//open the file in read only mode
// only if the file exist
ofstream MyFile("test.txt",ios::in | ios::nocreate);
if (MyFile.is_open()) {
MyFile << "File exist\n";
}
else {
cout << "Something went wrong";
}
MyFile.close();
}
+ 3
A simple function:
bool exist(string PATH)
{
ifstream fin;
fin.open(PATH.c_str());
return bool(fin);
}
Now, checking :
if(exist("a.txt"))
{
//fstream file;
//file.open("a.txt");
// Need to reopen file...
//Do Something
}
else
{
//Do Something
}
Or you may simply open the file in read only mode and check in if like this:
fstream file;
file.open("a.txt",ios::in);
if(file)
{
//Use the file for reading, or reopen using ios::out...
}
Note that if you open a file declared in the following way like this:
ofstream fout;
fstream fout2;
fout.open("a.txt");
fout2.open("a.txt",ios::out);
And check for if(fout), it will always return true, as if a.txt doesn't exist, ofstream creates the file for you...
So you will have to use ios::nocreate here to prevent new file creation...
+ 3
Hmm, I found info on the net that it is no longer a part of the standard library... 😅
In Visual Studio though, you may use ios::_Nocreate ...
Otherwise, you dont have much choices except these:
0) Open the file in input mode only , like in exist function, and check in if() //No alteration required...
1) Use the exist function, which is to be directly copied... //Simple and effective...
2) Define the ios::nocreate flag yourself...:
//Trying to find the code, will update if found...
+ 2
In C you could make this:
FILE* file = fopen("filename.txt","r");
if(file==NULL){ ... }
+ 1
hey guys, thanks for the replies. I tried the ios::nocreate way. But it's throwing nocreate is not a member of std ios. What should i do?
I've already included appropriate headers.
@emore @kinshuk
0
@kinshuk thanks, mate. I used ifstream ios::in and it worked out fine. :)