一行一行读入文本文件

下面是一个例子,它读入Autoexec.bat的第一行。
     #include <stdio.h>
    
#include <stdlib.h>
    
    
main()
    
{
    
FILE * fp;
    
char s[256];
    
if((fp = fopen("c://autoexec.bat", "r")) == NULL)
    
{
    
printf("Can't open file/n");
    
return;
    
}
    
fgets(s, 256, fp);
    
printf("Line1 : %s/n", s);
    
fclose(fp);
    

  //文件流和string的结合是最佳的:
    
#include <iostream>

    
#include <fstream>

    
#include <strstream>

    
#include <string>

    
using namespace std;

    
    
int main()

    
{

    
string line;

    
ifstream input("input.txt",ios::in);

    
strstream temp;

    
    
while(1)

    
{

    
getline(input,line);

    
if(input.eof()) break;

    
//一行数据已经存入line中,可以对其进行处理,此处只是将其输出

    
cout << line << endl;

    
}

    
input.close();

    
    
return 0;

    
}

使用get(   )和put(   )  
   
  #include   <fstream.h>  
  void   main()  
  {  
          fstream   File("test_file.txt",ios::out   |   ios::in   |   ios::binary);  
          char   ch;  
          ch='o';  
          File.put(ch);   //   将ch的内容写入文件  
          File.seekg(ios::beg);   //   定位至文件首部  
          File.get(ch);   //   读出一个字符  
          cout   <<   ch   <<   endl;   //   将其显示在屏幕上  
          File.close();  
  }  
使用read(   )和write(   )  
   
  #include   <fstream.h>  
  #include   <string.h>  
   
  void   main()  
  {  
          fstream   File("test_file.txt",ios::out   |   ios::in   |   ios::binary);  
          File.write(arr,5);   //   将前5个字符——"Hello"写入文件  
          File.seekg(ios::beg);   //   定位至文件首部  
          static   char   read_array[100000],readOne[1];   //   在此我将打算读出些数据  
          int   i   =   0;  
          do  
          {  
                  File.read(readOne,1);   //   读出1个字符  
                  if(readOne[0]=='s')  
                  {  
                      ...  
                  }  
                  i++;  
          }  
          File.close();  
  }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值