本文主要介紹了C++ 遍歷某個文件夾下所有文件的方法步驟,分享給大家,主要給自己留個筆記。。
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
|
#include<iostream> #include<string> #include<io.h> #include<cstdio> #include<cstdlib> #include<cstring> using namespace std; void fileSearch(string path) { long hFile = 0; /* _finddata_t 存儲文件各種信息的結(jié)構(gòu)體,<io.h>; */ struct _finddata_t fileInfo; string pathName; /* \\* 表示符合的所有文件; 沒有找到即文件夾為空,退出; assign 表示把 pathName清空并置為path; append 表示在末尾加上字符串; c_str 返回一個const char* 的臨時指針; _findfirst 搜索與指定的文件名稱匹配的第一個實例,若成功則返回第一個實例的句柄,否則返回-1L; 函數(shù)原型:long _findfirst( char *filespec, struct _finddata_t *fileinfo ); */ if ( ( hFile = _findfirst(pathName.assign(path).append( "\\*" ).c_str(), &fileInfo) ) == -1) return ; do { cout << path+ "\\" +fileInfo.name << endl; /* 文件夾下有 . 和 .. 目錄,不能進(jìn)入搜索; _A_SUBDIR 表示文件夾屬性; */ if ( strcmp (fileInfo.name, ".." ) && strcmp (fileInfo.name, "." ) && fileInfo.attrib==_A_SUBDIR ) fileSearch(path+ "\\" +fileInfo.name); } while ( _findnext(hFile, &fileInfo) == 0 ); /* _findnext 搜索與_findfirst函數(shù)提供的文件名稱匹配的下一個實例,若成功則返回0,否則返回-1 ; _findclose 結(jié)束查找; */ _findclose(hFile); return ; } int main() { string path= "E:\\Git" ; fileSearch(path); system ( "pause" ); return 0; } |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/sbfhy/p/10228360.html