C++常用文件操作

  • 文件是否存在
bool isFileExist(const std::string& fileName)
{
    std::ifstream fi(fileName);
    return fi;
}
  • 文件路径
std::string getFilePath(const std::string& fileName)
{
	size_t index = fileName.find_last_of("\\/");
	return fileName.substr(0, index + 1);
}
  • 文件夹选择对话框
#include <Shlobj.h> //getFilePathByDialog

//返回"",或者'\\'结尾的文件夹路径(vista风格)
std::string getFilePathByDialog()
{
	std::string path;
	IFileDialog *pfd;
	CoInitialize(0);
	if (SUCCEEDED(CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd))))
	{
		DWORD dwOptions;
		pfd->GetOptions(&dwOptions);
		pfd->SetOptions(dwOptions | FOS_PICKFOLDERS);

		if (SUCCEEDED(pfd->Show(NULL)))
		{
			IShellItem *psi;
			if (SUCCEEDED(pfd->GetResult(&psi)))
			{
				LPWSTR wc;
				if(SUCCEEDED(psi->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING,  &wc)))
				{
					char cs[1024];
					int len= WideCharToMultiByte(CP_ACP,0,wc,wcslen(wc),NULL,0,NULL,NULL);  
					WideCharToMultiByte(CP_ACP,0,wc,wcslen(wc),cs,len,NULL,NULL);
					if(cs[len-1] != '\\')
					{
						cs[len] = '\\';
						++len;
					}
					path.assign(cs, len);
				}
				CoTaskMemFree(wc);
				psi->Release();
			}
		}
		pfd->Release();
	}
	return path;
}
//简易风格
//char szBuffer[256];
//BROWSEINFO bi;   
//ZeroMemory(&bi,sizeof(BROWSEINFO));   
//ZeroMemory(szBuffer,sizeof(szBuffer));   
//bi.hwndOwner = NULL;   
//bi.pszDisplayName = szBuffer;   
//bi.lpszTitle = "选择图片根目录(路径相对于此目录):";   
//bi.ulFlags = BIF_RETURNFSANCESTORS;   
//LPITEMIDLIST idl = SHBrowseForFolder(&bi);   
//SHGetPathFromIDList(idl, szBuffer);   
//if (NULL == idl)   
//{   
//	return 0;   
//}   
//return 0;

 

  • 文件大小
#include <sys/stat.h>
size_t getFileSize(const char* fileName)
{
    struct _stat info;
    _stat(fileName, &info);
    return info.st_size;
}

 

  • 文件内容字符串
#include <fstream>
char* getFileData(const char* fileName, size_t* pFileSize) //需外部free(data)
{
    size_t fileSize = getFileSize(fileName);
    *pFileSize = fileSize;

    char* data = (char*)malloc(fileSize+1);
    data[fileSize] = '\0'; //便于作为字符串处理

    std::ifstream file;
    file.open(fileName, std::ios_base::binary);
    file.read(data, fileSize);
    file.close();

    return data;
}

 

 

  • 遍历文件夹
//头文件

#pragma once
typedef bool(*FileEnumFunc)(const char* path, bool isDir); //false停止遍历
extern void enumerateFile(const char* path, FileEnumFunc fun);
 

//代码文件:
#include "FileEnumerate.h"
#include <windows.h>
#include <stdio.h>

static FileEnumFunc _fun;

static void _enumerateFile(const char* path)
{
    char findPath[255];
    sprintf_s(findPath, "%s*", path);

    WIN32_FIND_DATA findData;
    HANDLE hFind;
    bool bContinue = true;

    hFind = FindFirstFile(findPath, &findData);
    if(hFind == INVALID_HANDLE_VALUE) return;

    while(bContinue)
    {
        if(strcmp(findData.cFileName, "..") && strcmp(findData.cFileName, "."))
        {
            if(findData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
            {
                sprintf_s(findPath, "%s%s\\", path, findData.cFileName);
                if(!_fun(findPath, true)) return;
                _enumerateFile(findPath);
            }
            else{
                sprintf_s(findPath, "%s%s", path, findData.cFileName);
                if(!_fun(findPath, false)) return;
            }
        }

        bContinue = FindNextFile(hFind, &findData);
    }
}

void enumerateFile(const char* path, FileEnumFunc fun)
{
    _fun = fun;
    size_t len = strlen(path);
    if(len>0 && path[len-1] == '\\')
    {
        _enumerateFile(path);
    }
    else
    {
        char pathFull[255];
        sprintf_s(pathFull, "%s\\", path);
        _enumerateFile(pathFull);
    }
}
  •  All

h

#pragma once
#include <string>
#ifdef WIN32
#include <io.h>
#include <direct.h> 
#else
#include <unistd.h>
#include <sys/stat.h>
#endif
//#include <stdint.h>

typedef bool(*FileEnumFunc)(const char* path, bool isDir); //false停止遍历
extern void enumerateFile(const char* path, FileEnumFunc fun, bool includeChildDir = true);

size_t getFileSize(const char* fileName);

//需外部free(data), 会在尾部多加个\0方便作为字符串处理
char* getFileData(const char* fileName, size_t* pFileSize);

bool isFileExist(const std::string& fileName);

std::string getFilePath(const std::string& fileName);

//返回"",或者'\\'结尾的文件夹路径(vista风格)
std::string getFilePathByDialog();

//创建目录
// 从左到右依次判断文件夹是否存在,不存在就创建
// example: /home/root/mkdir/1/2/3/4/
// 注意:最后一个如果是文件夹的话,需要加上 '\' 或者 '/'
int createDirectory(const std::string &directoryPath);
bool isDirExist(const char* dir);

 

cpp

#include <windows.h>
#include <stdio.h>

#include <fstream>
#include <sys/stat.h> //getFileSize
#include <Shlobj.h> //getFilePathByDialog

#include "utilfile.h"

size_t getFileSize(const char* fileName)
{
	struct _stat info;
	_stat(fileName, &info);
	return info.st_size;
}

char* getFileData(const char* fileName, size_t* pFileSize) //需外部free(data)
{
	size_t fileSize = getFileSize(fileName);
	*pFileSize = fileSize;

	char* data = (char*)malloc(fileSize+1);
	data[fileSize] = '\0'; //便于作为字符串处理

	std::ifstream file;
	file.open(fileName, std::ios_base::binary);
	file.read(data, fileSize);
	file.close();

	return data;
}

bool isFileExist(const std::string& fileName)
{
	std::ifstream fi(fileName);
	return fi;
}

std::string getFilePath(const std::string& fileName)
{
	size_t index = fileName.find_last_of("\\/");
	return fileName.substr(0, index + 1);
}

static FileEnumFunc _fun;
static void _enumerateFile(const char* path, bool includeChildDir)
{
	char findPath[255];
	sprintf_s(findPath, "%s*", path);

	WIN32_FIND_DATAA findData;
	HANDLE hFind;
	bool bContinue = true;

	hFind = FindFirstFileA(findPath, &findData);
	if(hFind == INVALID_HANDLE_VALUE) return;

	while(bContinue)
	{
		if(strcmp(findData.cFileName, "..") && strcmp(findData.cFileName, ".")) //不是当前目录或上级目录
		{
			if(findData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY)
			{
				if(includeChildDir)
				{
					sprintf_s(findPath, "%s%s\\", path, findData.cFileName);
					if(!_fun(findPath, true)) return;
					_enumerateFile(findPath, true);
				}
			}
			else{
				sprintf_s(findPath, "%s%s", path, findData.cFileName);
				if(!_fun(findPath, false)) return;
			}
		}

		bContinue = FindNextFileA(hFind, &findData);
	}
}
void enumerateFile(const char* path, FileEnumFunc fun, bool includeChildDir)
{
	_fun = fun;
	size_t len = strlen(path);
	if(len>0 && path[len-1] == '\\')
	{
		_enumerateFile(path, includeChildDir);
	}
	else
	{
		char pathFull[255];
		sprintf_s(pathFull, "%s\\", path);
		_enumerateFile(pathFull, includeChildDir);
	}
}

//返回"",或者'\\'结尾的文件夹路径(vista风格)
std::string getFilePathByDialog()
{
	std::string path;
	IFileDialog *pfd;
	CoInitialize(0);
	if (SUCCEEDED(CoCreateInstance(CLSID_FileOpenDialog, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&pfd))))
	{
		DWORD dwOptions;
		pfd->GetOptions(&dwOptions);
		pfd->SetOptions(dwOptions | FOS_PICKFOLDERS);

		if (SUCCEEDED(pfd->Show(NULL)))
		{
			IShellItem *psi;
			if (SUCCEEDED(pfd->GetResult(&psi)))
			{
				LPWSTR wc;
				if(SUCCEEDED(psi->GetDisplayName(SIGDN_DESKTOPABSOLUTEPARSING,  &wc)))
				{
					char cs[1024];
					int len= WideCharToMultiByte(CP_ACP,0,wc,wcslen(wc),NULL,0,NULL,NULL);  
					WideCharToMultiByte(CP_ACP,0,wc,wcslen(wc),cs,len,NULL,NULL);
					if(cs[len-1] != '\\')
					{
						cs[len] = '\\';
						++len;
					}
					path.assign(cs, len);
				}
				CoTaskMemFree(wc);
				psi->Release();
			}
		}
		pfd->Release();
	}
	return path;
}
//简易风格
//char szBuffer[256];
//BROWSEINFO bi;   
//ZeroMemory(&bi,sizeof(BROWSEINFO));   
//ZeroMemory(szBuffer,sizeof(szBuffer));   
//bi.hwndOwner = NULL;   
//bi.pszDisplayName = szBuffer;   
//bi.lpszTitle = "选择图片根目录(路径相对于此目录):";   
//bi.ulFlags = BIF_RETURNFSANCESTORS;   
//LPITEMIDLIST idl = SHBrowseForFolder(&bi);   
//SHGetPathFromIDList(idl, szBuffer);   
//if (NULL == idl)   
//{   
//	return 0;   
//}   
//return 0;


#define MAX_PATH_LEN 256
#ifdef WIN32
#define ACCESS(fileName,accessMode) _access(fileName,accessMode)
#define MKDIR(path) _mkdir(path)
#else
#define ACCESS(fileName,accessMode) access(fileName,accessMode)
#define MKDIR(path) mkdir(path,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)
#endif
// 从左到右依次判断文件夹是否存在,不存在就创建
// example: /home/root/mkdir/1/2/3/4/
// 注意:最后一个如果是文件夹的话,需要加上 '\' 或者 '/'

bool isDirExist(const char* dir)
{
	return ACCESS(dir, 0) == 0;
}

int createDirectory(const std::string &directoryPath)
{
	unsigned int dirPathLen = directoryPath.length();
	if (dirPathLen > MAX_PATH_LEN)
	{
		return -1;
	}
	char tmpDirPath[MAX_PATH_LEN] = { 0 };
	for (unsigned int i = 0; i < dirPathLen; ++i)
	{
		tmpDirPath[i] = directoryPath[i];
		if (tmpDirPath[i] == '\\' || tmpDirPath[i] == '/')
		{
			if (!isDirExist(tmpDirPath))
			{
				int ret = MKDIR(tmpDirPath);
				if (ret != 0)
				{
					return ret;
				}
			}
		}
	}
	return 0;
}

 

posted @ 2017-05-25 10:38  wiki3D  阅读(541)  评论(0编辑  收藏  举报