1. 程式人生 > >C++中判斷一個檔案是否存在的方法

C++中判斷一個檔案是否存在的方法

最進在寫的一個系統需要儲存結果資料,但是儲存結果資料的時候,如果那個資料已經存在,就會無法儲存,所以就需要先判斷是否存在該資料,判斷方法如下:

#include<iostream>
#include<fstream>

using namespace std;

int main()
{
	char *savePath = "/home/zhuwei/contour/linearIteration.shp";
        fstream f2;	

 	f2.open(savePath);
	if(!f2)
	{
		cout<<"檔案不存在"<<endl;
		f2.close();
	}
	else
	{
		cout<<"檔案存在"<<endl;
		f2.close();
	}
	return 0;
}

編譯:g++  -o fileexists fileexisttest.cpp

執行:./fileexists

OK,可以執行