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! :)

6th Jun 2017, 6:40 PM
anonymous
6 odpowiedzi
+ 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(); }
6th Jun 2017, 7:23 PM
Emore Anzolin
Emore Anzolin - avatar
+ 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...
7th Jun 2017, 3:33 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 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...
7th Jun 2017, 2:10 PM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 2
In C you could make this: FILE* file = fopen("filename.txt","r"); if(file==NULL){ ... }
7th Jun 2017, 12:13 AM
Andrés04_ve
Andrés04_ve - avatar
+ 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
7th Jun 2017, 1:47 PM
anonymous
0
@kinshuk thanks, mate. I used ifstream ios::in and it worked out fine. :)
7th Jun 2017, 2:53 PM
anonymous