判斷路徑文件夾是否存在,不存在建立
C/C++判斷一個文件是否存在
1.
bool isExistFile(const char *pszFileName){
FILE *fp = fopen(pszFileName, "rb");
if(fp == NULL)
return false;
fclose(fp);
return true;
}
或
bool isExistFile(const char *pszFileName){
fstream file;
file.open(pszFileName,ios::in);
if(!file)
return false;ios
return true;
}windows
2.利用 c 語言的庫的辦法:
函數名: access函數
// crt_access.c
#include <io.h>
#include <stdio.h>
#include <stdlib.h>spa
int main( void )
{
/* Check for existence */
if( (_access( "crt_ACCESS.C", 0 )) != -1 )
{
printf( "File crt_ACCESS.C exists\n" );
/* Check for write permission */
/* assume file is read-only */
if( (_access( "crt_ACCESS.C", 2 )) == -1 )
printf( "File crt_ACCESS.C does not have write permission\n" );
}
}日誌
3.用FindFirstFiletoken
#include <windows.h>
#include <string>
#include <vector>
using namespace std; string
// 覈查目錄,若目錄不存在,建立目錄
bool FindOrCreateDirectory( const char* pszPath )
{
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile( pszPath, &fd );
while( hFind != INVALID_HANDLE_VALUE )
{
if ( fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
return true;
}it
if ( !::CreateDirectory( pszPath, NULL ) )
{
char szDir[MAX_PATH];
sprintf_s( szDir, sizeof(szDir), "建立目錄[%s]失敗,請檢查權限", pszPath );
::MessageBox( NULL, szDir, "建立目錄失敗", MB_OK|MB_ICONERROR );
return false;
}io
return true;
}test
// 遍歷目錄
bool CheckDirectory( char* pszPath )
{
vector< std::string > vtPath;
const char* sep = "\\/";
char* next_token;
char* token = strtok_s( pszPath, sep, &next_token);
while( token != NULL )
{
vtPath.push_back( token );
token = strtok_s(NULL, sep, &next_token);
}
if ( vtPath.size() > 0 )
{
if ( vtPath[0] == "." )
vtPath.erase( vtPath.begin() );
}
// 覈查全部路徑是否存在
std::string strCurPath;
for( size_t i = 0; i < (int)vtPath.size(); ++i )
{
strCurPath += vtPath[i];
strCurPath += '\\';
if ( !FindOrCreateDirectory( strCurPath.c_str() ) )
{
return false;
}
}
return true;
}
int main() { char szPath[MAX_PATH] = "./main\\test\\hello/jump\\test\\"; CheckDirectory( szPath ); FILE *m_file; // 日誌文件 strcpy(m_file, szPath); strcat(m_file, "FileName.txt") m_file = fopen(szPath + m_sFileName.c_str(), "a+"); fprintf(m_file, "%s\n", "想寫神馬就寫神馬."); fclose(m_file); m_file = NULL; system("pause"); return 0; }