精華區beta C_and_CPP 關於我們 聯絡資訊
問題在描述一下 我想要由使用者定義 要讀檔案的位置 然後 把每個檔案讀取進來 做我需要的運算 開發工具 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)
james732:推,這類問題還挺多人問的! 03/12 19:09
loveme00835:推推 03/12 21:38
prime2477:推 03/12 21:40
> -------------------------------------------------------------------------- < 作者: yoco315 (眠月) 看板: C_and_CPP 標題: Re: [心得] dev c++讀取資料夾裡面每一個檔案? 時間: Sat Mar 13 00:10:45 2010 ※ 引述《alohaiscool (aloha)》之銘言: : 問題在描述一下 : 我想要由使用者定義 要讀檔案的位置 然後 把每個檔案讀取進來 做我需要的運算 好文,我也貢獻一個 qq ┌────────────────────────────────────┐ #include <boost/filesystem.hpp>int main () {namespace fs = boost::filesystem ;typedef fs::directory_iterator dir_iter ;for ( dir_iter i("."); i!=dir_iter(); ++i ) {// 如果是一般的檔案,不是目錄或是link之類的... if ( fs::is_regular_file ( i->status() ) ) {std::ifstream fin ( i->path().file_string().c_str() ) ;// 對 fin 做事 }}}└────────────────────────────────────┘ 其實這是我第一次用 boost::filesystem ="= 以前我都用 system ( "dir/b > _" ) XD -- To iterate is human, to recurse, divine. 遞迴只應天上有, 凡人該當用迴圈.   L. Peter Deutsch -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.160.117.71
sunneo:gj 03/13 01:27
tropical72:好像都沒人拉一個 listbox 來用厚.. lb->Dir 03/13 03:19
nowar100:一看到上色版就知道是yoco大了 XD 03/13 06:59