创建多级目录

时间:2022-07-07 12:14:12

 

 

  1 #include <iostream>
2 #include <stdlib.h>
3 #include <string>
4 #include <string.h>
5
6 using namespace std;
7
8
9 #pragma warning(disable: 4996)
10
11
12 #ifdef _WIN32
13 #include <direct.h>
14 #include <io.h>
15 #elif _LINUX
16 #include <stdarg.h>
17 #include <sys/stat.h>
18 #endif
19
20 #ifdef _WIN32
21 #define ACCESS _access
22 #define MKDIR(a) _mkdir((a))
23 #elif _LINUX
24 #define ACCESS access
25 #define MKDIR(a) mkdir((a),0755)
26 #endif
27
28
29
30 int CreatDir( char *pDir )
31 {
32 int i = 0;
33 int iRet;
34 int iLen;
35 char* pszDir;
36
37 if ( NULL == pDir )
38 {
39 return 0;
40 }
41
42 int len = strlen( pDir );
43 pszDir = new char[len+1];
44 strcpy(pszDir,pDir);
45
46 iLen = strlen( pszDir );
47
48 // 创建中间目录
49 for ( i = 0; i < iLen; i++ )
50 {
51 if ( pszDir[i] == '\\' || pszDir[i] == '/' )
52 {
53 pszDir[i] = '\0';
54
55 //如果不存在,创建
56 iRet = ACCESS( pszDir, 0 ); //参数为0时表示检查文件的存在性,如果文件存在,返回0,不存在,返回-1。
57 if ( iRet != 0 )
58 {
59 iRet = MKDIR( pszDir ); //建立新目录
60 if ( iRet != 0 )
61 {
62 return -1;
63 }
64 }
65 //支持linux,将所有\换成/
66 pszDir[i] = '/';
67 }
68 }
69
70 iRet = MKDIR( pszDir );
71
72 delete[] pszDir;
73 pszDir = NULL;
74
75 return iRet;
76 }
77
78
79
80 void main()
81 {
82
83 char* pc = "E:/Save/Game/object/123/abc/1.txt";
84
85 cout << "Original: " << pc << endl;
86
87 string name( pc );
88
89 int iPonit = name.find( "Game" );
90
91 name.insert(iPonit,"ResBak/");
92
93 int i = name.find_last_of("/");
94
95 name = name.substr(0,i);
96
97 cout << "Name: " << name << endl;
98
99 const int len = name.length();
100
101 pc = NULL;
102 pc = new char[len + 1];
103
104 strcpy( pc, name.c_str() );
105
106 cout << "Pc: " << pc << endl;
107
108
109 int Result = CreatDir( pc );
110
111 delete[] pc;
112 pc = NULL;
113
114 system( "pause" );
115 }

 

 

创建多级目录