曾在工作中遇见一个特别问题,就是在使用fstream中getline方法读数据读不出。如下:
1 #include <iostream> 2 #include <fstream> 3 #include <string> 4 #include <vector> 5 6 using namespace std; 7 8 int _tmain(int argc, _TCHAR* argv[]) 9 { 10 vector<string> vstr; 11 12 fstream file1("d:\\test1.txt"); 13 14 fstream file2("d:\\test2.txt"); 15 16 fstream file3("d:\\test3.txt"); 17 18 while(!file1.eof()) 19 { 20 char buf[MAX_PATH]; 21 22 file1.getline(buf,sizeof(buf)); 23 24 string getStr = string((const char*)buf); 25 26 if(string::npos != getStr.find('?',0)) 27 { 28 29 string str = getStr.substr(0,getStr.find('\t',0)); 30 31 vstr.push_back(str); 32 } 33 } 34 35 while(!file2.eof()) 36 { 37 char buf[MAX_PATH]; 38 39 file2.getline(buf1,sizeof(buf1)); 40 41 string getStr1 = string((const char*)buf1); 42 43 for(int i=0; i < vstr.size();i++) 44 { 45 if(string::npos != getStr1.find(vstr[i],0)) 46 { 47 48 file3<<getStr1<<endl; 49 50 break; 51 } 52 } 53 } 54 55 file1.close(); 56 57 file2.close(); 58 59 file3.close(); 60 61 return 0; 62 }
后来,灵机一想改用File中fgets来读就行。如下
#include <stdio.h> #include <fstream> #include <string> #include <vector> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { vector<string> vstr; FILE *pFile1,*pFile2,*pFile3; pFile1 = fopen("d:\\file1.txt"); pFile1 = fopen("d:\\file2.txt"); pFile1 = fopen("d:\\file3.txt"); if(NULL ==pFile1 || NULL ==pFile2 || NULL == PFile3) { exit(); } while(!feof(pFile1) { char buf[MAX_PATH]; if ((NULL==fgets(buf,sizeof(buf),pFile1))?TRUE:FALSE) return; string getStr = string((const char*)buf); if(string::npos != getStr.find('?',0)) { string str = getStr.substr(0,getStr.find('\t',0)); vstr.push_back(str); } } while(!feof(pFile2)) { char buf[MAX_PATH]; if ((NULL==fgets(buf,sizeof(buf),pFile2)?TRUE:FALSE) return; string getStr1 = string((const char*)buf1); for(int i=0; i < vstr.size();i++) { if(string::npos != getStr1.find(vstr[i],0)) { fputs(getStr1,pFile3); break; } } } fclose(pFile1); fclose(pFile2); fclose(pFile3); return 0; }