VC++文件相关操作的函数封装实现

在开发编译工具中,需要用到文件的相关操作,于是就封装了相关的函数实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//判断文件是否存在
BOOL FileIsExist(CString strFileName)
{
    CFileFind finder;
    BOOL bWorking = finder.FindFile(strFileName);
    while(bWorking)
    {
        return TRUE;
    }
    return FALSE;
}
//获取ini文件信息
CString GetIniString(CString strAppName, CString strKeyName, CString strDefault, CString strFileName)
{
    CString strRet;
    const int nMaxLength = 1024;
    GetPrivateProfileString(strAppName, strKeyName, strDefault,strRet.GetBuffer(nMaxLength), nMaxLength,strFileName);
    strRet.ReleaseBuffer();
    return strRet;
}
 
// 得到文件的后缀名
CString GetFileExtension(CString fileName)
{
    CString strFileNameExt = TEXT("");
 
    int nPosExt = fileName.ReverseFind(TEXT(‘.‘));
    strFileNameExt = fileName.Right(fileName.GetLength() - nPosExt - 1);
    return strFileNameExt;
}
 
 
//获取运行路径
CString GetRunPath()
{
 
    TCHAR cbFilename[MAX_PATH + 1]={‘\0‘};
    GetModuleFileName(NULL, cbFilename, MAX_PATH);
    CString strPath=cbFilename;
    strPath=strPath.Left(strPath.ReverseFind(‘\\‘));
    return strPath;
}
 
// 根据一个路径创建目录
void CreatePath(CString strPath)
{
    CString dirName;
    CString strSub;
    CString strDrive;
    int nPos = 0;
 
    nPos = strPath.Find(TEXT(":"));
    dirName = strPath.Right(strPath.GetLength() - nPos -1);
    strDrive = strPath.Left(nPos + 1);
    int ia = 1;
    while (1)
    {
        AfxExtractSubString(strSub, dirName, ia, TEXT(‘\\‘));
        if (TEXT("") == strSub)
        {
            break;
        }
        ia++;
        strDrive += TEXT("\\") + strSub;
        if (!PathFileExists(strDrive))
        {
            CreateDirectory(strDrive, NULL);
        }
    }
}
 
 
 
// 删除一个目录下的所有文件
bool DeleteDirFiles(CString strDir)
{
    //   CreateDirectory(strDir, NULL);
    CreatePath(strDir);
    CFileFind finder;
    CString strFindDir;
 
    strFindDir.Format(TEXT("%s\\*.*"), strDir);
    //   MessageBox(strFindDir);
    BOOL bWorking = finder.FindFile(strFindDir);
    while(bWorking)
    {
        bWorking = finder.FindNextFile();
 
        if (!finder.IsDirectory())
        {
            DeleteFile(finder.GetFilePath());
        }
    }
    finder.Close();
    return false;
}
 
//根据路径获取文件名
CString GetFileNameFromPath(CString strPath)
{
    CString strDirName = TEXT("");
 
    int nPos = strPath.ReverseFind(TEXT(‘\\‘));
    if (-1 != nPos)
    {
        strDirName = strPath.Right(strPath.GetLength() - nPos -1);
    }
 
    return strDirName;
}

  

VC++文件相关操作的函数封装实现

上一篇:(原创)用c++11打造好用的variant(更新)


下一篇:C语言文件操作函数大全