方法1:利用fstream 和ifstream
(1)用fstream
#include <iostream>
#include <fstream>
using namespace std;
#define FILENAME "test.txt"
int main()
{
fstream _file;
_file.open(FILENAME,ios::in); //注意,此处必须为in,若为out或app,则在文件不存在的情况下,程序会创建文件
if(!_file)
{
cout<<FILENAME<<"没有被创建";
}
else
{
cout<<FILENAME<<"已经存在";
}
return 0;
}
(2)用ifstream
#include <iostream>
#include <fstream>
using namespace std;
#define FILENAME "test.txt"
int main()
{
ifstream _file;
_file.open(FILENAME,ios::out); //注意,此处的模式不重要
if(!_file)
{
cout<<FILENAME<<"没有被创建";
}
else
{
cout<<FILENAME<<"已经存在";
}
return 0;
}
(3)用ofstream
#include <iostream>
#include <fstream>
using namespace std;
#define FILENAME "test.txt"
int main()
{
ofstream _file;
_file.open(FILENAME,ios::in); //注意,此处必须为in,若为out或app,则在文件不存在的情况下,程序会创建文件
if(!_file)
{
cout<<FILENAME<<"没有被创建";
}
else
{
cout<<FILENAME<<"已经存在";
}
return 0;
}
方法2: 利用c语言的函数
#include <io.h>
#include <iostream>
using namespace std;
int main( void )
{
/* Check for existence */
if( (_access( "main.cpp", 0 )) != -1 )
{
cout<<"文件存在"<<endl;
/* Check for write permission */
if( (_access( "ACCESS.C", 2 )) != -1 )
cout<<"文件可写"<<endl;
else
cout<<"文件不可写"<<endl;
}
else
cout<<"文件不存在"<<endl;
return 0;
}
详细见:http://msdn.microsoft.com/en-us/library/1w06ktdy(v=vs.80).aspx
access(filename, num)
num的几种情况(对文件操作的模式):
0-检查文件是否存在
1-检查文件是否可运行
2-检查文件是否可写访问
4-检查文件是否可读访问
6-检查文件是否可读/写访问
3.在windows平台下用API函数FindFirstFile(...):
(1)检查文件是否存在:
#define _WIN32_WINNT 0x0400
#include "windows.h"
intmain(int argc, char *argv[])
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind;
printf ({WIN32_FIND_DATA FindFileData;HANDLE hFind;
printf ("Target file is %s. ", argv[1]);
hFind
hFind = FindFirstFile(argv[1], &FindFileData);
if (hFind == INVALID_HANDLE_VALUE) {
printf (printf ("Invalid File Handle. Get Last Error reports %d ", GetLastError ());
}} else {
printf (printf ("The first file found is %s ", FindFileData.cFileName);
FindClose(hFind);
}
FindClose(hFind);}
return (0);
}
}
(2)检查某一目录是否存在:
///目录是否存在的检查:bool CheckFolderExist(const string &strPath)
{
WIN32_FIND_DATA wfd;
{WIN32_FIND_DATA wfd;bool rValue = false;
HANDLE hFindHANDLE hFind = FindFirstFile(strPath.c_str(), &wfd);
if ((hFind != INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
{
rValue{rValue = true;
}
FindClose(hFind);
}FindClose(hFind);return rValue;
}
}
4.使用boost的filesystem类库的exists函数
#include <boost/filesystem/operations.hpp>#include <boost/filesystem/path.hpp>#include <boost/filesystem/convenience.hpp>
int GetFilePath(std::string &strFilePath)
{
{string strPath;
int nRes = 0;
//指定路径strPath = "D:/myTest/Test1/Test2";
namespace fs = boost::filesystem;
//路径的可移植fs::path full_path( fs::initial_path() );full_path = fs::system_complete( fs::path(strPath, fs::native ) );
//判断各级子目录是否存在,不存在则需要创建if ( !fs::exists( full_path ) )
{
{// 创建多层子目录bool bRet = fs::create_directories(full_path);
if (false == bRet)
{
{return -1 ;
}
}
strFilePath}
}strFilePath = full_path.native_directory_string();
return 0;
}}