[心得] dev c++讀取資料夾裡面每一個檔案?

看板C_and_CPP作者 (aloha)時間15年前 (2010/03/12 18:38), 編輯推噓5(501)
留言6則, 6人參與, 最新討論串1/2 (看更多)
問題在描述一下 我想要由使用者定義 要讀檔案的位置 然後 把每個檔案讀取進來 做我需要的運算 開發工具 dev c++ 主要兩種方法 我自己改編過 (寫得很爛請見諒,但是對於新手應該比較很好懂) 第一種 使用 #include <dirent.h> #include <iostream> #include <dirent.h> #include <string> #include <iomanip> #include <fstream> using namespace std; int main() { DIR *D; struct dirent *Dirpath ifstream fin; cout<<"please input the file path \n" ; cout<<"path:" ; string filepath; getline(cin,filepath); D = opendir(filepath.c_str()); while (Dirpath = readdir(D)) { if( strcmp(Dirpath->d_name, ".") != 0 && strcmp(Dirpath->d_name, "..") != 0 ) //如果不加上面那一行 讀取出來的檔案會有點點 { string file_in=filepath+Dirp->d_name; //這邊我卡很久...因為會讀不到檔案,最後突然靈光一閃要給他絕對位置 fin.open(file_in.c_str(),ios::in|ios::binary); if (fin.is_open()) { while(!fin.eof()) { //這邊就放你要做的事情} } else {cout<<"file open error\n";} fin.close(); } } system("PAUSE"); return 0; } 第二種是 使用#include <window.h> 網路上找到的 #include <windows.h> #include <iostream> #include <fstream> #include <string> #include <cstdlib> using namespace std; int main() { string path; cout<<"please input the file location (file need to scaled)\n" ; cout<<"location:" ; getline(cin,path); string searchPattern = "*.*"; string fullSearchPath = path + searchPattern; WIN32_FIND_DATA FindData; HANDLE hFind; hFind = FindFirstFile( fullSearchPath.c_str(), &FindData ); if( hFind == INVALID_HANDLE_VALUE ) { cout << "Error searching directory\n"; return -1; } do { string filePath = path + FindData.cFileName; ifstream in( filePath.c_str() ); if( in ) { while(!in.eof()) { //這邊就放你要做的事情 } } else { cout << "Problem opening file " << FindData.cFileName << "\n"; } }while( FindNextFile(hFind, &FindData) > 0 ); if( GetLastError() != ERROR_NO_MORE_FILES ) { cout << "Something went wrong during searching\n"; } system("pause"); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.174.25 ※ 編輯: alohaiscool 來自: 140.112.174.25 (03/12 18:41)

03/12 19:09, , 1F
推,這類問題還挺多人問的!
03/12 19:09, 1F

03/12 21:38, , 2F
推推
03/12 21:38, 2F

03/12 21:40, , 3F
03/12 21:40, 3F

03/12 22:21, , 4F
我都呆呆用system("dir")>>rec.log
03/12 22:21, 4F

03/13 00:05, , 5F
dos的也有_dos_findfirst 同windows
03/13 00:05, 5F

03/13 00:11, , 6F
推推
03/13 00:11, 6F
文章代碼(AID): #1BcXcY0j (C_and_CPP)
文章代碼(AID): #1BcXcY0j (C_and_CPP)