VC创建文件夹和文件

本文简单介绍下VC创建文件夹和文件。


新建对话框应用程序,然后添加全局变量函数

BOOL FolderExist(CString strPath)
{
	WIN32_FIND_DATA wfd;
	BOOL bValue=FALSE;
	HANDLE hFind=::FindFirstFile(strPath,&wfd);
	if( (hFind!=INVALID_HANDLE_VALUE) && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )//文件找到
	{
		bValue = TRUE;
	}
	::FindClose(hFind);
	return bValue;
}

BOOL CreateFolder(CString strPath)
{
	SECURITY_ATTRIBUTES attrib;
    attrib.bInheritHandle = FALSE;
    attrib.lpSecurityDescriptor = NULL;
    attrib.nLength = sizeof(SECURITY_ATTRIBUTES);
    return ::CreateDirectory(strPath, &attrib);
//	return ::CreateDirectory(strPath,NULL);
}

在程序界面上添加按钮

此程序首先获取当前系统时间和当前程序路径,然后在该路径下生成一个MyFolder的文件夹,然后在该文件夹内部生成一个文件名为MyFile+当前时间,后缀为.txt,内容为My Folder and File test!的文件。

void CCreateFolderAndFileDlg::OnButton1() 
{
	//获取系统时间
	SYSTEMTIME SystemTime;
	::GetLocalTime(&SystemTime);
	CString str="",Date="";
	str.Format("%02d",SystemTime.wYear);
	Date = Date + str;
	str.Format("_%02d",SystemTime.wMonth);
	Date = Date + str;
	str.Format("_%02d",SystemTime.wDay);
	Date = Date + str;
	str.Format("_%02d",SystemTime.wHour);
	Date = Date + str;
	str.Format("_%02d",SystemTime.wMinute);
	Date = Date + str;
	str.Format("_%02d",SystemTime.wSecond);
	Date = Date + str;

	//获取当前路径
	CString sCurrentPath = "";
	char Path[270];
	DWORD len = 0;
	DWORD i=0;
	len = GetCurrentDirectory(270,Path);
	for (i=0; i<len; i++)
	{
		sCurrentPath = sCurrentPath + CString(Path[i]);
	}

	//指定的文件夹
	CString sMyFilePath = "";
	sMyFilePath = sCurrentPath + "\\MyFolder";

	//创建文件夹
	if(!FolderExist(sMyFilePath))//文件存在
	{
		if(!CreateFolder(sMyFilePath))//创建文件
		{
			return;
		}
	}

	//创建文件
	CString sFilePathName = "";
	sFilePathName = sMyFilePath + "\\MyFile" + "_" + Date + ".txt";
	//打开
	CStdioFile MyFile;
	CFileException ex;
	if(!MyFile.Open(sFilePathName,CFile::modeCreate | CFile::modeWrite | CFile::typeText,&ex))
	{
		ex.ReportError();
		return;
	}
	//写入
	MyFile.WriteString("My Folder and File test!");
	//关闭
	MyFile.Close();

	MessageBox("文件创建成功!");
}

运行程序,查看效果





查看程序中的文件夹和文件,发现多了这样一个文件夹



打开文件夹,发现多了这样一个文件



打开文件,查看内容

VC创建文件夹和文件_第1张图片


源码下载


你可能感兴趣的:(创建,文件,文件夹,VC)