对文件读取的几种方法

1.系统调用

  1 #include <sys/types.h>
  2 #include <sys/stat.h>
  3 #include <fcntl.h>
  4 #include <unistd.h>
  5
  6 #include <string.h>
  7
  8
  9 #include <iostream>
 10
 11 using namespace std;
 12
 13 int main()
 14 {
 15     int fd = open("/etc/exports", O_RDONLY);
 16
 17     char buf[10240];
 18     int nread = read(fd, buf, 10240);
 19     close(fd);
 20
 21     cout << buf << endl;
 22
 23     cout << "parsing " << endl;
 24
 25     char* saveptr;
 26     char* token = strtok_r(buf, "\n", &saveptr);
 27     cout << "line 1:" << token << endl;
 28
 29     int counter = 1;
 30     while(NULL != (token = strtok_r(NULL, "\n", &saveptr)))
 31     {
 32         counter++;
 33         cout << "line "<< counter << ":" << token <<endl;
 34     }
 35
 36     cout << "==========\nend" << endl;
 37     return 0;
 38 }

2C语言API

 1 #include <sys/types.h>
  2 #include <sys/stat.h>
  3 #include <fcntl.h>
  4 #include <unistd.h>
  5
  6 #include <string.h>
  7 #include <stdio.h>
  8
  9 #include <iostream>
 10
 11 using namespace std;
 12
 13 int main()
 14 {
 15     FILE* fp = fopen("/etc/exports", "r");
 16
 17     char line[1024];
 18     int counter = 1;
 19     while(NULL != fgets(line, 1024, fp))
 20     {
 21         cout << "line " << counter <<":"<< line ;
 22         counter++;
 23     }
 24
 25     fclose(fp);
 26     cout << "==========\nend" << endl;
 27     return 0;
 28 }

C++流

 1 #include <sys/types.h>
  2 #include <sys/stat.h>
  3 #include <fcntl.h>
  4 #include <unistd.h>
  5
  6 #include <string.h>
  7
  8
  9 #include <fstream>
 10 #include <iostream>
 11
 12 using namespace std;
 13
 14 int main()
 15 {
 16     ifstream fin("/etc/exports");
 17     int counter = 1;
 18     string line;
 19     while(!fin.eof())
 20     {
 21         getline(fin, line);
 22         cout << "line "<< counter << ":" << line <<endl;
 23         counter++;
 24     }
 25
 26     fin.close();
 27
 28     cout << "==========\nend" << endl;
 29     return 0;
 30 }

STL加泛型算法

  1 #include <iostream>
  2 #include <vector>
  3 #include <iterator>
  4 #include <algorithm>
  5 #include <fstream>
  6
  7 using namespace std;
  8
  9 int main()
 10 {
 11
 12     ifstream fin("/etc/exports");
 13     vector<string> content;
 14
 15     istream_iterator<string> begin(fin);
 16     istream_iterator<string> end;
 17
 18     copy(begin, end, back_inserter(content));
 19
 20     cout << "content" << endl;
 21
 22     copy(content.begin(), content.end(),
 23
 24             ostream_iterator<string>(cout, "\n"));
 25
 26     return 0;
 27 }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值