Filesystem.cpp 16.6 KB
Newer Older
1
2
3
#include <Filesystem.h>
#include <sys/stat.h>
#include <sys/types.h>
liucong's avatar
liucong committed
4
5

#include <algorithm>
6
#include <fstream>
liucong's avatar
liucong committed
7

8
9
#ifdef _WIN32
#include <Windows.h>
liucong's avatar
liucong committed
10
11
12
#include <direct.h>
#include <io.h>

13
14
#else
#include <dirent.h>
liucong's avatar
liucong committed
15
16
#include <unistd.h>

17
18
19
20
#endif

// 路径分隔符(Linux:‘/’,Windows:’\\’)
#ifdef _WIN32
liucong's avatar
liucong committed
21
#define PATH_SEPARATOR '\\'
22
#else
liucong's avatar
liucong committed
23
#define PATH_SEPARATOR '/'
24
25
#endif

liucong's avatar
liucong committed
26
27
using namespace std;

liucong's avatar
liucong committed
28
namespace migraphxSamples {
29

liucong's avatar
liucong committed
30
31
32
33
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
34
35
    str += separator; // 扩展字符串以方便操作
    int size = str.size();
liucong's avatar
liucong committed
36

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

50
#if defined _WIN32 || defined WINCE
liucong's avatar
liucong committed
51
const char dir_separators[] = "/\\";
52

liucong's avatar
liucong committed
53
54
55
56
struct dirent
{
    const char* d_name;
};
57

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

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

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

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

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

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

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

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

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

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

void Remove(const string& directory, const string& extension)
{
    DIR* dir;

    static int numberOfFiles = 0;
444

liucong's avatar
liucong committed
445
    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
578
579
580
581
    if(result == -1)
    {
        return IsDirectory(path);
    }
    return true;
}

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

liucong's avatar
liucong committed
583
584
585
586
    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
    return CreateDirectory(path);
}
614

liucong's avatar
liucong committed
615
616
617
618
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
    if(!srcFile.is_open())
    {
        printf("can not open %s\n", srcPath.c_str());
        return false;
624
    }
liucong's avatar
liucong committed
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
    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;
646
647
}

liucong's avatar
liucong committed
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
bool CopyDirectories(string srcPath, const string dstPath)
{
    if(srcPath == dstPath)
    {
        printf("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;
        printf("%s done! %f% \n", GetFileName(fileNameList[i]).c_str(), process);
    }
    printf("all done!(the number of files:%d)\n", fileNameList.size());

    return true;
}
697

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