Filesystem.cpp 14.7 KB
Newer Older
Your Name's avatar
Your Name committed
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
#include <Filesystem.h>
#include <algorithm>
#include <sys/stat.h>
#include <sys/types.h>
#include <fstream>
#ifdef _WIN32
#include <io.h>
#include <direct.h>
#include <Windows.h>
#else
#include <unistd.h>
#include <dirent.h>
#endif
#include <CommonUtility.h>
#include <opencv2/opencv.hpp>
#include <SimpleLog.h>

using namespace cv;
 
// 路径分隔符(Linux:‘/’,Windows:’\\’)
#ifdef _WIN32
#define  PATH_SEPARATOR '\\'
#else
#define  PATH_SEPARATOR '/'
#endif

namespace migraphxSamples
{

#if defined _WIN32 || defined WINCE
    const char dir_separators[] = "/\\";

	struct dirent
	{
		const char* d_name;
	};

	struct DIR
	{
#ifdef WINRT
		WIN32_FIND_DATAW data;
#else
        WIN32_FIND_DATAA data;
#endif
		HANDLE handle;
		dirent ent;
#ifdef WINRT
		DIR() { }
		~DIR()
		{
			if (ent.d_name)
				delete[] ent.d_name;
		}
#endif
	};

	DIR* opendir(const char* path)
	{
		DIR* dir = new DIR;
		dir->ent.d_name = 0;
#ifdef WINRT
		string full_path = string(path) + "\\*";
		wchar_t wfull_path[MAX_PATH];
		size_t copied = mbstowcs(wfull_path, full_path.c_str(), MAX_PATH);
		CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
		dir->handle = ::FindFirstFileExW(wfull_path, FindExInfoStandard,
			&dir->data, FindExSearchNameMatch, NULL, 0);
#else
		dir->handle = ::FindFirstFileExA((string(path) + "\\*").c_str(),
			FindExInfoStandard, &dir->data, FindExSearchNameMatch, NULL, 0);
#endif
		if (dir->handle == INVALID_HANDLE_VALUE)
		{
			/*closedir will do all cleanup*/
			delete dir;
			return 0;
		}
		return dir;
	}

	dirent* readdir(DIR* dir)
	{
#ifdef WINRT
		if (dir->ent.d_name != 0)
		{
			if (::FindNextFileW(dir->handle, &dir->data) != TRUE)
				return 0;
		}
		size_t asize = wcstombs(NULL, dir->data.cFileName, 0);
		CV_Assert((asize != 0) && (asize != (size_t)-1));
		char* aname = new char[asize + 1];
		aname[asize] = 0;
		wcstombs(aname, dir->data.cFileName, asize);
		dir->ent.d_name = aname;
#else
		if (dir->ent.d_name != 0)
		{
			if (::FindNextFileA(dir->handle, &dir->data) != TRUE)
				return 0;
		}
		dir->ent.d_name = dir->data.cFileName;
#endif
		return &dir->ent;
	}

	void closedir(DIR* dir)
	{
		::FindClose(dir->handle);
		delete dir;
	}
#else
# include <dirent.h>
# include <sys/stat.h>
	const char dir_separators[] = "/";
#endif

	static bool isDir(const string &path, DIR* dir)
	{
#if defined _WIN32 || defined WINCE
		DWORD attributes;
		BOOL status = TRUE;
		if (dir)
			attributes = dir->data.dwFileAttributes;
		else
		{
			WIN32_FILE_ATTRIBUTE_DATA all_attrs;
#ifdef WINRT
			wchar_t wpath[MAX_PATH];
			size_t copied = mbstowcs(wpath, path.c_str(), MAX_PATH);
			CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
			status = ::GetFileAttributesExW(wpath, GetFileExInfoStandard, &all_attrs);
#else
			status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs);
#endif
			attributes = all_attrs.dwFileAttributes;
		}

		return status && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
#else
		(void)dir;
		struct stat stat_buf;
		if (0 != stat(path.c_str(), &stat_buf))
			return false;
		int is_dir = S_ISDIR(stat_buf.st_mode);
		return is_dir != 0;
#endif
	}

	bool IsDirectory(const string &path)
	{
		return isDir(path, NULL);
	}

	bool Exists(const string& path)
	{

#if defined _WIN32 || defined WINCE
			BOOL status = TRUE;
		{
			WIN32_FILE_ATTRIBUTE_DATA all_attrs;
#ifdef WINRT
			wchar_t wpath[MAX_PATH];
			size_t copied = mbstowcs(wpath, path.c_str(), MAX_PATH);
			CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
			status = ::GetFileAttributesExW(wpath, GetFileExInfoStandard, &all_attrs);
#else
			status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs);
#endif
		}

		return !!status;
#else
		struct stat stat_buf;
		return (0 == stat(path.c_str(), &stat_buf));
#endif
	}

    bool IsPathSeparator(char c)
    {
        return c == '/' || c == '\\';
	}

	string JoinPath(const string& base, const string& path)
	{
		if (base.empty())
			return path;
		if (path.empty())
			return base;

		bool baseSep = IsPathSeparator(base[base.size() - 1]);
		bool pathSep = IsPathSeparator(path[0]);
		string result;
		if (baseSep && pathSep)
		{
			result = base + path.substr(1);
		}
		else if (!baseSep && !pathSep)
		{
            result = base + PATH_SEPARATOR + path;
		}
		else
		{
			result = base + path;
		}
		return result;
	}

	static bool wildcmp(const char *string, const char *wild)
	{
		const char *cp = 0, *mp = 0;

		while ((*string) && (*wild != '*'))
		{
			if ((*wild != *string) && (*wild != '?'))
			{
				return false;
			}

			wild++;
			string++;
		}

		while (*string)
		{
			if (*wild == '*')
			{
				if (!*++wild)
				{
					return true;
				}

				mp = wild;
				cp = string + 1;
			}
			else if ((*wild == *string) || (*wild == '?'))
			{
				wild++;
				string++;
			}
			else
			{
				wild = mp;
				string = cp++;
			}
		}

		while (*wild == '*')
		{
			wild++;
		}

		return *wild == 0;
	}

	static void glob_rec(const string &directory, const string& wildchart, std::vector<string>& result,
		bool recursive, bool includeDirectories, const string& pathPrefix)
	{
		DIR *dir;

		if ((dir = opendir(directory.c_str())) != 0)
		{
			/* find all the files and directories within directory */
			try
			{
				struct dirent *ent;
				while ((ent = readdir(dir)) != 0)
				{
					const char* name = ent->d_name;
					if ((name[0] == 0) || (name[0] == '.' && name[1] == 0) || (name[0] == '.' && name[1] == '.' && name[2] == 0))
						continue;

					string path = JoinPath(directory, name);
					string entry = JoinPath(pathPrefix, name);

					if (isDir(path, dir))
					{
						if (recursive)
							glob_rec(path, wildchart, result, recursive, includeDirectories, entry);
						if (!includeDirectories)
							continue;
					}

					if (wildchart.empty() || wildcmp(name, wildchart.c_str()))
						result.push_back(entry);
				}
			}
			catch (...)
			{
				closedir(dir);
				throw;
			}
			closedir(dir);
		}
		else
		{
			LOG_INFO(stdout, "could not open directory: %s", directory.c_str());
		}
	}

	void GetFileNameList(const string &directory, const string &pattern, std::vector<string>& result, bool recursive, bool addPath)
	{
        // split pattern
        vector<string> patterns=SplitString(pattern,",");

        result.clear();

        for(int i=0;i<patterns.size();++i)
        {
            string eachPattern=patterns[i];
            std::vector<string> eachResult;
            glob_rec(directory, eachPattern, eachResult, recursive, true, directory);
            for(int j=0;j<eachResult.size();++j)
            {
				if (IsDirectory(eachResult[j]))
					continue;
                if(addPath)
                {
                    result.push_back(eachResult[j]);
                }
                else
                {
                    result.push_back(GetFileName(eachResult[j]));
                }
            }
        }
		std::sort(result.begin(), result.end());
	}

	void GetFileNameList2(const string &directory, const string &pattern, std::vector<string>& result, bool recursive, bool addPath)
	{
		// split pattern
		vector<string> patterns = SplitString(pattern, ",");

        result.clear();

		for (int i = 0; i<patterns.size(); ++i)
		{
			string eachPattern = patterns[i];
			std::vector<string> eachResult;
			glob_rec(directory, eachPattern, eachResult, recursive, true, directory);
			for (int j = 0; j<eachResult.size(); ++j)
			{
				string filePath = eachResult[j];
				if (IsDirectory(filePath))
				{
					filePath = filePath + "/";
					for (int k = 0; k < filePath.size(); ++k)
					{
						if (IsPathSeparator(filePath[k]))
						{
							filePath[k] = '/';
						}
					}
				}
				if (addPath)
				{
					result.push_back(filePath);
				}
				else
				{
					if (!IsDirectory(filePath))
					{
						result.push_back(GetFileName(filePath));
					}
				}
			}
		}
		std::sort(result.begin(), result.end());
	}

	void RemoveAll(const string& path)
	{

		if (!Exists(path))
			return;

		if (IsDirectory(path))
		{
			std::vector<string> entries;
			GetFileNameList2(path, string(), entries, false, true);
			for (size_t i = 0; i < entries.size(); i++)
			{
				const string& e = entries[i];
				RemoveAll(e);
			}
#ifdef _MSC_VER
			bool result = _rmdir(path.c_str()) == 0;
#else
			bool result = rmdir(path.c_str()) == 0;
#endif
			if (!result)
			{
				LOG_INFO(stdout, "can't remove directory: %s\n", path.c_str());
			}
		}
		else
		{
#ifdef _MSC_VER
			bool result = _unlink(path.c_str()) == 0;
#else
			bool result = unlink(path.c_str()) == 0;
#endif
			if (!result)
			{
				LOG_INFO(stdout, "can't remove file: %s\n", path.c_str());
			}
		}
	}

	void Remove(const string &directory, const string &extension)
	{

		DIR *dir;

		static int numberOfFiles = 0;

		if ((dir = opendir(directory.c_str())) != 0)
		{
			/* find all the files and directories within directory */
			try
			{
				struct dirent *ent;
				while ((ent = readdir(dir)) != 0)
				{
					const char* name = ent->d_name;
					if ((name[0] == 0) || (name[0] == '.' && name[1] == 0) || (name[0] == '.' && name[1] == '.' && name[2] == 0))
						continue;

					string path = JoinPath(directory, name);

					if (isDir(path, dir))
					{
						Remove(path, extension);
					}

					// �ж���չ��
					if (extension.empty() || wildcmp(name, extension.c_str()))
					{
						RemoveAll(path);
						++numberOfFiles;
						LOG_INFO(stdout, "%s deleted! number of deleted files:%d\n", path.c_str(), numberOfFiles);
					}

				}
			}
			catch (...)
			{
				closedir(dir);
				throw;
			}
			closedir(dir);
		}
		else
		{
			LOG_INFO(stdout, "could not open directory: %s", directory.c_str());
		}

		// ����RemoveAllɾ��Ŀ¼
		RemoveAll(directory);
	}
	string GetFileName(const string &path)
	{
        string fileName;
        int indexOfPathSeparator = -1;
        for (int i = path.size() - 1; i >= 0; --i)
        {
            if (IsPathSeparator(path[i]))
            {
                fileName = path.substr(i + 1, path.size() - i - 1);
                indexOfPathSeparator = i;
                break;
            }
        }
        if (indexOfPathSeparator == -1)
        {
            fileName = path;
        }

        return fileName;
	}
    string GetFileName_NoExtension(const string &path)
    {
        string fileName=GetFileName(path);
        string fileName_NoExtension;
        for(int i=fileName.size()-1;i>0;--i)
        {
            if(fileName[i]=='.')
            {
                fileName_NoExtension=fileName.substr(0,i);
                break;
            }
        }

        return fileName_NoExtension;
    }

	string GetExtension(const string &path)
	{
		string fileName;
		for (int i = path.size() - 1; i >= 0; --i)
		{
			if (path[i]=='.')
			{
				fileName = path.substr(i, path.size() - i);
				break;
			}
		}

		return fileName;

	}

	string GetParentPath(const string &path)
	{
		string fileName;
		for (int i = path.size() - 1; i >= 0; --i)
		{
			if (IsPathSeparator(path[i]))
			{
				fileName = path.substr(0, i+1);
				break;
			}
		}

		return fileName;
	}

    static bool CreateDirectory(const string &path)
    {
    #if defined WIN32 || defined _WIN32 || defined WINCE
    #ifdef WINRT
                wchar_t wpath[MAX_PATH];
            size_t copied = mbstowcs(wpath, path.c_str(), MAX_PATH);
            CV_Assert((copied != MAX_PATH) && (copied != (size_t)-1));
            int result = CreateDirectoryA(wpath, NULL) ? 0 : -1;
    #else
                int result = _mkdir(path.c_str());
    #endif
    #elif defined __linux__ || defined __APPLE__
                int result = mkdir(path.c_str(), 0777);
    #else
                int result = -1;
    #endif

            if (result == -1)
            {
                return IsDirectory(path);
            }
            return true;
    }

	bool CreateDirectories(const string &directoryPath)
	{
		string path = directoryPath;

		for (;;)
		{
			char last_char = path.empty() ? 0 : path[path.length() - 1];
			if (IsPathSeparator(last_char))
			{
				path = path.substr(0, path.length() - 1);
				continue;
			}
			break;
		}

		if (path.empty() || path == "./" || path == ".\\" || path == ".")
			return true;
		if (IsDirectory(path))
			return true;

		size_t pos = path.rfind('/');
		if (pos == string::npos)
			pos = path.rfind('\\');
		if (pos != string::npos)
		{
			string parent_directory = path.substr(0, pos);
			if (!parent_directory.empty())
			{
				if (!CreateDirectories(parent_directory))
					return false;
			}
		}

		return CreateDirectory(path);
	}

    bool CopyFile(const string srcPath, const string dstPath)
    {
        std::ifstream srcFile(srcPath,ios::binary);
        std::ofstream dstFile(dstPath,ios::binary);

        if(!srcFile.is_open())
        {
            LOG_ERROR(stdout,"can not open %s\n",srcPath.c_str());
            return false;
        }
        if(!dstFile.is_open())
        {
			LOG_ERROR(stdout, "can not open %s\n", dstPath.c_str());
            return false;
        }
        if(srcPath==dstPath)
        {
			LOG_ERROR(stdout, "src can not be same with dst\n");
            return false;
        }
        char buffer[2048];
        unsigned int numberOfBytes=0;
        while(srcFile)
        {
            srcFile.read(buffer,2048);
            dstFile.write(buffer,srcFile.gcount());
            numberOfBytes+=srcFile.gcount();
        }
        srcFile.close();
        dstFile.close();
        return true;
    }

    bool CopyDirectories(string srcPath, const string dstPath)
    {
        if(srcPath==dstPath)
        {
			LOG_ERROR(stdout, "src can not be same with dst\n");
            return false;
        }

		// ȥ������·���ָ���
		srcPath = srcPath.substr(0, srcPath.size() - 1);

        vector<string> fileNameList;
        GetFileNameList2(srcPath, "", fileNameList, true, true);

        string parentPathOfSrc=GetParentPath(srcPath);
        int length=parentPathOfSrc.size();

        // create all directories
        for(int i=0;i<fileNameList.size();++i)
        {
            // create directory
            string srcFilePath=fileNameList[i];
            string subStr=srcFilePath.substr(length,srcFilePath.size()-length);
            string dstFilePath=dstPath+subStr;
            string parentPathOfDst=GetParentPath(dstFilePath);
            CreateDirectories(parentPathOfDst);
        }

        // copy file
        for(int i=0;i<fileNameList.size();++i)
        {
            string srcFilePath=fileNameList[i];
			if (IsDirectory(srcFilePath))
			{
				continue;
			}
            string subStr=srcFilePath.substr(length,srcFilePath.size()-length);
            string dstFilePath=dstPath+subStr;

            // copy file
            CopyFile(srcFilePath,dstFilePath);

			// process
			double process = (1.0*(i + 1) / fileNameList.size()) * 100;
			LOG_INFO(stdout, "%s done! %f% \n", GetFileName(fileNameList[i]).c_str(), process);
        }
		LOG_INFO(stdout, "all done!(the number of files:%d)\n", fileNameList.size());

        return true;


    }

}