[問題] 陣列與讀檔
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
wxDev-C++ 然後用 Linux 下的 mpiCC compile
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
none
問題(Question):
預設兩個常數 const int N=200, size=50;
存放檔名的陣列 char *NamePtr[N], FName[N*size];
利用 opendir 找出資料夾內的檔案
得知資料夾內的檔名 ( 存放在 NamePtr ) 和檔案數 nfile
利用 std::ifstream fp; 和 input 的路徑 一個一個開檔
char HD[50]; 暫存檔案的內容
fp >> HD; // 問題所在 !!!
fp.close(); 關檔
======
當沒有 fp >> HD 也就是沒有讀內容的話 一切沒問題
但 fp >> HD 出現 且 開到第三個檔案時
NamePtr[2] 第三個檔案的檔名 就變成 第二個檔案的內容...
接著當掉....
餵入的資料(Input):
慾處理檔案的資料夾路徑
預期的正確結果(Expected Output):
沒有當掉 NamePtr 也沒被改掉...
錯誤結果(Wrong Output):
NamePtr 被改了
程式碼(Code):(請善用置底文網頁, 記得排版)
bool cvt (char* dir)
{
const int N=200, size=50;
char *NamePtr[N], FName[N*size];
for (int i=0; i<N; i+=1)
NamePtr[i]=&FName[i*size];
DIR *d=opendir(dir);
dirent *d_ent;
int nfile=0;
while((d_ent=readdir(d)) ){
NamePtr[nfile]=d_ent -> d_name;
nfile++;}
closedir(d);
char HD[50];
std::ifstream fp;
char FNdir[200];
for (int inxF = 0; inxF < nfile; inxF += 1){
sprintf(FNdir, "%s%s", dir, NamePtr[inxF]);
fp.open (FNdir);
fp>>HD; // 關鍵行
fp.close();}
return 0;
} // end of cvt
int main(int argc,char **argv)
{
cvt(argv[1]);
return 0;
}
補充說明(Supplement):
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.109.113.229
※ 編輯: MikePhysics 來自: 140.109.113.229 (02/15 15:09)
推
02/15 15:09, , 1F
02/15 15:09, 1F
→
02/15 15:10, , 2F
02/15 15:10, 2F
→
02/15 15:12, , 3F
02/15 15:12, 3F
→
02/15 15:12, , 4F
02/15 15:12, 4F
推
02/15 15:16, , 5F
02/15 15:16, 5F
→
02/15 15:19, , 6F
02/15 15:19, 6F
→
02/15 15:35, , 7F
02/15 15:35, 7F
→
02/15 15:36, , 8F
02/15 15:36, 8F
※ 編輯: MikePhysics 來自: 140.109.113.229 (02/15 15:37)
→
02/15 17:38, , 9F
02/15 17:38, 9F
→
02/15 17:39, , 10F
02/15 17:39, 10F
→
02/15 17:51, , 11F
02/15 17:51, 11F
→
02/15 18:01, , 12F
02/15 18:01, 12F
推
02/15 18:52, , 13F
02/15 18:52, 13F
→
02/15 18:53, , 14F
02/15 18:53, 14F
→
02/15 18:55, , 15F
02/15 18:55, 15F
→
02/15 18:55, , 16F
02/15 18:55, 16F