C标准库 io.h源码 检查文件是否存在

来源:互联网 发布:淘宝查看付款排名 编辑:程序博客网 时间:2024/04/30 16:50
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>


bool isFileExist(const char *filename){
    if( _access(filename, 0) == 0 ) {
        // exist
        printf("Exist %s\n",filename);
    }else{
        printf("Not exist %s\n",filename);
    }
    return true;
}


int main(){
    isFileExist("c:\\boot.ini");
    isFileExist("c:\\bootmgr");
    return 0;

}

测试结果:

>gcc test.cpp

>a
Not exist c:\boot.ini
Exist c:\bootmgr


=====================================================================================


这个头文件 外围的条件编译是非 posix。windows平台 还有 CreateFile啊,GetFileAttributeEx啊,FindFirstFile

BOOL FindFirstFileExists(LPCTSTR lpPath, DWORD dwFilter)
{
  WIN32_FIND_DATA fd;
  HANDLE hFind = FindFirstFile(lpPath, &fd);
  BOOL bFilter = (FALSE == dwFilter) ? TRUE : fd.dwFileAttributes & dwFilter;
  BOOL RetValue = ((hFind != INVALID_HANDLE_VALUE) && bFilter) ? TRUE : FALSE;
  FindClose(hFind);
  return RetValue;
}

// 检查一个路径是否存在(绝对路径、相对路径,文件或文件夹均可)
BOOL FilePathExists(LPCTSTR lpPath)
{
  return FindFirstFileExists(lpPath, FALSE);
}

// 检查一个文件夹是否存在(绝对路径、相对路径均可)
BOOL FolderExists(LPCTSTR lpPath)
{
  return FindFirstFileExists(lpPath, FILE_ATTRIBUTE_DIRECTORY);
}

HANDLE FindFirstFileEx(
  LPCTSTR lpFileName, // file name
  FINDEX_INFO_LEVELS fInfoLevelId, // information level
  LPVOID lpFindFileData, // information buffer
  FINDEX_SEARCH_OPS fSearchOp, // filtering type
  LPVOID lpSearchFilter, // search criteria
  DWORD dwAdditionalFlags // reserved
);

 

 

 

都是些 windows平台的函数。不是跨平台的。微软 真是 烦人。


0 0