<C++>FILE和fstream

原文地址:http://www.cnblogs.com/virgil/p/3841717.html

曾在工作中遇见一个特别问题,就是在使用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);     
3233   }  
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       }
5253   }  
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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值