Filesystem.cpp 16.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#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

// 路径分隔符(Linux:‘/’,Windows:’\\’)
#ifdef _WIN32
liucong's avatar
liucong committed
17
#define PATH_SEPARATOR '\\'
18
#else
liucong's avatar
liucong committed
19
#define PATH_SEPARATOR '/'
20
21
#endif

liucong's avatar
liucong committed
22
23
using namespace std;

24
25
26
namespace migraphxSamples
{

liucong's avatar
liucong committed
27
28
29
30
static std::vector<std::string> SplitString(std::string str, std::string separator)
{
    std::string::size_type pos;
    std::vector<std::string> result;
liucong's avatar
liucong committed
31
32
    str += separator; // 扩展字符串以方便操作
    int size = str.size();
liucong's avatar
liucong committed
33

liucong's avatar
liucong committed
34
    for(int i = 0; i < size; i++)
liucong's avatar
liucong committed
35
    {
liucong's avatar
liucong committed
36
37
        pos = str.find(separator, i);
        if(pos < size)
liucong's avatar
liucong committed
38
        {
liucong's avatar
liucong committed
39
            std::string s = str.substr(i, pos - i);
liucong's avatar
liucong committed
40
            result.push_back(s);
liucong's avatar
liucong committed
41
            i = pos + separator.size() - 1;
liucong's avatar
liucong committed
42
43
44
45
46
        }
    }
    return result;
}

47
#if defined _WIN32 || defined WINCE
liucong's avatar
liucong committed
48
const char dir_separators[] = "/\\";
49

liucong's avatar
liucong committed
50
51
52
53
struct dirent
{
    const char* d_name;
};
54

liucong's avatar
liucong committed
55
56
struct DIR
{
57
#ifdef WINRT
liucong's avatar
liucong committed
58
    WIN32_FIND_DATAW data;
59
#else
liucong's avatar
liucong committed
60
    WIN32_FIND_DATAA data;
61
#endif
liucong's avatar
liucong committed
62
63
    HANDLE handle;
    dirent ent;
64
#ifdef WINRT
liucong's avatar
liucong committed
65
66
67
68
69
70
    DIR() {}
    ~DIR()
    {
        if(ent.d_name)
            delete[] ent.d_name;
    }
71
#endif
liucong's avatar
liucong committed
72
};
73

liucong's avatar
liucong committed
74
75
76
77
DIR* opendir(const char* path)
{
    DIR* dir        = new DIR;
    dir->ent.d_name = 0;
78
#ifdef WINRT
liucong's avatar
liucong committed
79
80
81
82
83
84
    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);
85
#else
liucong's avatar
liucong committed
86
87
88
89
90
91
    dir->handle = ::FindFirstFileExA((string(path) + "\\*").c_str(),
                                     FindExInfoStandard,
                                     &dir->data,
                                     FindExSearchNameMatch,
                                     NULL,
                                     0);
92
#endif
liucong's avatar
liucong committed
93
94
95
96
97
98
99
100
101
102
103
    if(dir->handle == INVALID_HANDLE_VALUE)
    {
        /*closedir will do all cleanup*/
        delete dir;
        return 0;
    }
    return dir;
}

dirent* readdir(DIR* dir)
{
104
#ifdef WINRT
liucong's avatar
liucong committed
105
106
107
108
109
110
111
112
113
114
115
    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;
116
#else
liucong's avatar
liucong committed
117
118
119
120
121
122
    if(dir->ent.d_name != 0)
    {
        if(::FindNextFileA(dir->handle, &dir->data) != TRUE)
            return 0;
    }
    dir->ent.d_name = dir->data.cFileName;
123
#endif
liucong's avatar
liucong committed
124
125
126
127
128
129
130
131
    return &dir->ent;
}

void closedir(DIR* dir)
{
    ::FindClose(dir->handle);
    delete dir;
}
132
#else
liucong's avatar
liucong committed
133
134
135
#include <dirent.h>
#include <sys/stat.h>
const char dir_separators[] = "/";
136
137
#endif

liucong's avatar
liucong committed
138
139
static bool isDir(const string& path, DIR* dir)
{
140
#if defined _WIN32 || defined WINCE
liucong's avatar
liucong committed
141
142
143
144
145
146
147
    DWORD attributes;
    BOOL status = TRUE;
    if(dir)
        attributes = dir->data.dwFileAttributes;
    else
    {
        WIN32_FILE_ATTRIBUTE_DATA all_attrs;
148
#ifdef WINRT
liucong's avatar
liucong committed
149
150
151
152
        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);
153
#else
liucong's avatar
liucong committed
154
        status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs);
155
#endif
liucong's avatar
liucong committed
156
157
        attributes = all_attrs.dwFileAttributes;
    }
158

liucong's avatar
liucong committed
159
    return status && ((attributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
160
#else
liucong's avatar
liucong committed
161
162
163
164
165
166
    (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;
167
#endif
liucong's avatar
liucong committed
168
}
169

liucong's avatar
liucong committed
170
bool IsDirectory(const string& path) { return isDir(path, NULL); }
171

liucong's avatar
liucong committed
172
173
bool Exists(const string& path)
{
174
175

#if defined _WIN32 || defined WINCE
liucong's avatar
liucong committed
176
177
178
    BOOL status = TRUE;
    {
        WIN32_FILE_ATTRIBUTE_DATA all_attrs;
179
#ifdef WINRT
liucong's avatar
liucong committed
180
181
182
183
        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);
184
#else
liucong's avatar
liucong committed
185
        status = ::GetFileAttributesExA(path.c_str(), GetFileExInfoStandard, &all_attrs);
186
#endif
liucong's avatar
liucong committed
187
    }
188

liucong's avatar
liucong committed
189
    return !!status;
190
#else
liucong's avatar
liucong committed
191
192
    struct stat stat_buf;
    return (0 == stat(path.c_str(), &stat_buf));
193
#endif
liucong's avatar
liucong committed
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
}

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 != '?'))
230
        {
liucong's avatar
liucong committed
231
232
233
234
235
236
237
238
239
240
241
242
            return false;
        }

        wild++;
        string++;
    }

    while(*string)
    {
        if(*wild == '*')
        {
            if(!*++wild)
243
            {
liucong's avatar
liucong committed
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
                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
    {
        printf("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)
376
                {
liucong's avatar
liucong committed
377
378
379
380
                    if(IsPathSeparator(filePath[k]))
                    {
                        filePath[k] = '/';
                    }
381
                }
liucong's avatar
liucong committed
382
383
384
385
386
387
388
389
            }
            if(addPath)
            {
                result.push_back(filePath);
            }
            else
            {
                if(!IsDirectory(filePath))
390
                {
liucong's avatar
liucong committed
391
                    result.push_back(GetFileName(filePath));
392
393
394
                }
            }
        }
liucong's avatar
liucong committed
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
    }
    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);
        }
414
#ifdef _MSC_VER
liucong's avatar
liucong committed
415
        bool result = _rmdir(path.c_str()) == 0;
416
#else
liucong's avatar
liucong committed
417
        bool result = rmdir(path.c_str()) == 0;
418
#endif
liucong's avatar
liucong committed
419
420
421
422
423
424
425
        if(!result)
        {
            printf("can't remove directory: %s\n", path.c_str());
        }
    }
    else
    {
426
#ifdef _MSC_VER
liucong's avatar
liucong committed
427
        bool result = _unlink(path.c_str()) == 0;
428
#else
liucong's avatar
liucong committed
429
        bool result = unlink(path.c_str()) == 0;
430
#endif
liucong's avatar
liucong committed
431
        if(!result)
432
        {
liucong's avatar
liucong committed
433
            printf("can't remove file: %s\n", path.c_str());
434
        }
liucong's avatar
liucong committed
435
436
437
438
439
    }
}

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

liucong's avatar
liucong committed
441
442
443
444
445
    DIR* dir;

    static int numberOfFiles = 0;

    if((dir = opendir(directory.c_str())) != 0)
446
    {
liucong's avatar
liucong committed
447
448
        /* find all the files and directories within directory */
        try
449
        {
liucong's avatar
liucong committed
450
451
            struct dirent* ent;
            while((ent = readdir(dir)) != 0)
452
            {
liucong's avatar
liucong committed
453
454
455
456
                const char* name = ent->d_name;
                if((name[0] == 0) || (name[0] == '.' && name[1] == 0) ||
                   (name[0] == '.' && name[1] == '.' && name[2] == 0))
                    continue;
457

liucong's avatar
liucong committed
458
459
460
461
462
463
464
465
466
467
468
469
470
471
                string path = JoinPath(directory, name);

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

                // �ж���չ��
                if(extension.empty() || wildcmp(name, extension.c_str()))
                {
                    RemoveAll(path);
                    ++numberOfFiles;
                    printf("%s deleted! number of deleted files:%d\n", path.c_str(), numberOfFiles);
                }
472
            }
liucong's avatar
liucong committed
473
474
        }
        catch(...)
475
        {
liucong's avatar
liucong committed
476
477
            closedir(dir);
            throw;
478
        }
liucong's avatar
liucong committed
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
        closedir(dir);
    }
    else
    {
        printf("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]))
496
        {
liucong's avatar
liucong committed
497
498
499
            fileName             = path.substr(i + 1, path.size() - i - 1);
            indexOfPathSeparator = i;
            break;
500
        }
liucong's avatar
liucong committed
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
    }
    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] == '.')
516
        {
liucong's avatar
liucong committed
517
518
            fileName_NoExtension = fileName.substr(0, i);
            break;
519
        }
liucong's avatar
liucong committed
520
521
522
523
524
525
526
527
528
529
530
    }

    return fileName_NoExtension;
}

string GetExtension(const string& path)
{
    string fileName;
    for(int i = path.size() - 1; i >= 0; --i)
    {
        if(path[i] == '.')
531
        {
liucong's avatar
liucong committed
532
533
            fileName = path.substr(i, path.size() - i);
            break;
534
535
536
        }
    }

liucong's avatar
liucong committed
537
538
539
540
541
542
543
    return fileName;
}

string GetParentPath(const string& path)
{
    string fileName;
    for(int i = path.size() - 1; i >= 0; --i)
544
    {
liucong's avatar
liucong committed
545
        if(IsPathSeparator(path[i]))
546
        {
liucong's avatar
liucong committed
547
548
            fileName = path.substr(0, i + 1);
            break;
549
        }
liucong's avatar
liucong committed
550
    }
551

liucong's avatar
liucong committed
552
553
    return fileName;
}
554

liucong's avatar
liucong committed
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
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
571

liucong's avatar
liucong committed
572
573
574
575
576
577
    if(result == -1)
    {
        return IsDirectory(path);
    }
    return true;
}
578

liucong's avatar
liucong committed
579
580
581
582
583
584
585
586
bool CreateDirectories(const string& directoryPath)
{
    string path = directoryPath;

    for(;;)
    {
        char last_char = path.empty() ? 0 : path[path.length() - 1];
        if(IsPathSeparator(last_char))
587
        {
liucong's avatar
liucong committed
588
589
            path = path.substr(0, path.length() - 1);
            continue;
590
        }
liucong's avatar
liucong committed
591
592
        break;
    }
593

liucong's avatar
liucong committed
594
595
596
597
598
599
600
601
602
603
604
605
    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())
606
        {
liucong's avatar
liucong committed
607
608
            if(!CreateDirectories(parent_directory))
                return false;
609
        }
liucong's avatar
liucong committed
610
    }
611

liucong's avatar
liucong committed
612
613
614
615
616
617
618
    return CreateDirectory(path);
}

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

liucong's avatar
liucong committed
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
    if(!srcFile.is_open())
    {
        printf("can not open %s\n", srcPath.c_str());
        return false;
    }
    if(!dstFile.is_open())
    {
        printf("can not open %s\n", dstPath.c_str());
        return false;
    }
    if(srcPath == dstPath)
    {
        printf("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;
}
647

liucong's avatar
liucong committed
648
649
650
651
652
653
bool CopyDirectories(string srcPath, const string dstPath)
{
    if(srcPath == dstPath)
    {
        printf("src can not be same with dst\n");
        return false;
654
655
    }

liucong's avatar
liucong committed
656
657
658
659
660
    // ȥ������·���ָ���
    srcPath = srcPath.substr(0, srcPath.size() - 1);

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

liucong's avatar
liucong committed
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
    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;
        printf("%s done! %f% \n", GetFileName(fileNameList[i]).c_str(), process);
    }
    printf("all done!(the number of files:%d)\n", fileNameList.size());

    return true;
}
698

liucong's avatar
liucong committed
699
} // namespace migraphxSamples