您当前的位置: 首页 >  c++

phymat.nico

暂无认证

  • 0浏览

    0关注

    1967博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

如何利用C/C++逐行读取txt文件中的字符串(可以顺便实现文本文件的复制)

phymat.nico 发布时间:2017-12-05 15:40:55 ,浏览量:0

 原文地址:  http://blog.csdn.net/stpeace/article/details/12404925

如下代码均在Windows/VC++6.0下测试通过, 请一定注意linux和Windows文件格式的区别微笑微笑微笑

       先用C语言写一个丑陋的程序:

[cpp] view plain copy
  1. #include   
  2. #include   
  3. int main()  
  4. {  
  5.     FILE *fp;  
  6.     if(NULL == (fp = fopen("1.txt", "r")))  
  7.     {  
  8.         printf("error\n");  
  9.         exit(1);  
  10.     }  
  11.   
  12.     char ch;  
  13.     while(EOF != (ch=fgetc(fp)))  
  14.     {  
  15.         printf("%c", ch);  
  16.     }  
  17.   
  18.     fclose(fp);  
  19.   
  20.     return 0;  
  21. }  

     你只能看到结果,却没法利用每一行。 我们来改为:

[cpp] view plain copy
  1. // VC++6.0  
  2.   
  3. #include   
  4. #include   
  5.   
  6. int main()  
  7. {  
  8.     char szTest[1000] = {0};  
  9.     int len = 0;  
  10.   
  11.     FILE *fp = fopen("1.txt", "r");  
  12.     if(NULL == fp)  
  13.     {  
  14.         printf("failed to open dos.txt\n");  
  15.         return 1;  
  16.     }  
  17.   
  18.     while(!feof(fp))  
  19.     {  
  20.         memset(szTest, 0, sizeof(szTest));  
  21.         fgets(szTest, sizeof(szTest) - 1, fp); // 包含了\n  
  22.         printf("%s", szTest);  
  23.     }  
  24.   
  25.     fclose(fp);  
  26.   
  27.     printf("\n");  
  28.   
  29.     return 0;  
  30. }  

      这样, 我们就是整行读取了。

      感觉C的读取方法有点丑陋,还是看看C++吧:

[cpp] view plain copy
  1. #include   
  2. #include   
  3. #include   
  4. using namespace std;  
  5.   
  6. int main()  
  7. {  
  8.     ifstream in("1.txt");  
  9.     string filename;  
  10.     string line;  
  11.   
  12.     if(in) // 有该文件  
  13.     {  
  14.         while (getline (in, line)) // line中不包括每行的换行符  
  15.         {   
  16.             cout 
关注
打赏
1659628745
查看更多评论
立即登录/注册

微信扫码登录

0.0445s