1. 程式人生 > >windows讀取資料夾下所有的檔案——C++

windows讀取資料夾下所有的檔案——C++

                intptr_t hFile = 0;
                struct _finddata_t fileInfo;
                std::string pathName, exdName;
                if ((hFile = _findfirst(pathName.assign(path).append("\\*").c_str(), &fileInfo)) == -1) {
                    return;
                }
                do
{ std::cout << fileInfo.name << std::endl; // read the file if (strcmp(fileInfo.name, ".") != 0 && strcmp(fileInfo.name, "..") != 0) { std::ifstream file(path + "\\" + fileInfo.name); std
::string eachRow; std::stringstream stringStream; if (file) { while (!file.eof()) { std::getline(file, eachRow); //std::cout << eachRow << std::endl; if
(!eachRow.empty()) { // replace "," with blank for (int i = 0; i < eachRow.length(); i++) { if (eachRow[i] == ',') { eachRow[i] = ' '; } } //std::cout << eachRow << std::endl; // get every word from a row std::string updateEachRecord = "insert into _"; updateEachRecord.append(date); updateEachRecord.append("(InstrumentID,TradeDate,UpdateTime,UpdateMillisec,LastPrice,Volume,BidPrice1,BidVolume1,AskPrice1,AskVolume1,OpenInterest,Turnover) value ('"); std::string tempWord; stringStream.str(eachRow); stringStream >> tempWord; updateEachRecord.append(tempWord); updateEachRecord.append("',"); updateEachRecord.append(date); while (stringStream >> tempWord) { updateEachRecord.append(",'"); updateEachRecord.append(tempWord); updateEachRecord.append("'"); } updateEachRecord.append(")"); std::cout << updateEachRecord << std::endl; stringStream.clear(); // update the record to mysql; num = mysql_query(&mysql2, const_cast<char *>(updateEachRecord.c_str())); if (num == 0) { std::cout << "Succeed to update the record to mysql!" << std::endl; su++; } else { std::cout << "Fail to update the record to mysql! Error code = " << num << std::endl; getchar(); fa++; } } } } else { std::cout << "The file " << fileInfo.name << " is empty!" << std::endl; } } } while (_findnext(hFile, &fileInfo) == 0); _findclose(hFile);

注意標頭檔案為io.h,首先取出來的兩個檔案的名字分別為.和..,表示當前目錄和上一層目錄,需要剔除掉這兩種情況。