C++读取文件内容的方法

1 #include <iostream>
  2 #include <string>
  3 #include <vector>
  4 #include <fstream>
  5 #include <sstream>
  6 
  7 using namespace std;
  8 
  9 void readFile1(void)
 10 {
 11     ifstream ifs("test.txt");
 12     if (!ifs)
 13     {cout << "File open error!" << endl; exit(1);}
 14 
 15     // (1)逐个单词读取,以空格为分隔符。
 16     vector<string> iVec;
 17     iVec.reserve(500);
 18 
 19     string context;
 20     while (!ifs.eof())
 21     {
 22         ifs >> context;
 23         iVec.push_back(context);
 24     }
 25 
 26     copy(iVec.begin(), iVec.end(), ostream_iterator<string>(cout, ""));
 27     cout << endl;
 28     ifs.close();
 29 }
 30 
 31 void readFile2(void)
 32 {
 33     ifstream ifs("test.txt");
 34     if (!ifs)
 35     {cout << "File open error!" << endl; exit(1);}
 36 
 37     // (2)一次性将文件的内容读入,并且内容保持不变。
 38     ostringstream buffer;
 39     buffer << ifs.rdbuf();
 40     string context(buffer.str());
 41 
 42     cout << context << endl;
 43     ifs.close();
 44 }
 45 
 46 void readFile3(void)
 47 {
 48     ifstream ifs("test.txt");
 49     if (!ifs)
 50     {cout << "File open error!" << endl; exit(1);}
 51 
 52     // (3)一次性将文件的内容读入,但是过滤了所有空格符。
 53     istream_iterator<char> beg(ifs), end;
 54     string context(beg, end);
 55 
 56     cout << context << endl;
 57     ifs.close();
 58 }
 59 
 60 void readFile4(void)
 61 {
 62     ifstream ifs("test.txt");
 63     if (!ifs)
 64     {cout << "File open error!" << endl; exit(1);}
 65 
 66     // 获取文件大小。
 67     ifs.seekg(0, ios::end);
 68     streampos pos = ifs.tellg();
 69     ifs.seekg(0, ios::beg);  // 注意要将文件指针移动到文件头
 70 
 71     // (4)一次性将文件的内容读入,并且内容保持不变。
 72     if (pos > 0)
 73     {
 74         char* buff = new char[pos];
 75         ifs.read(buff, pos);
 76         for (int i = 0; i < pos; i++)
 77             cout << buff[i];
 78         cout << endl;
 79 
 80         delete []buff;
 81     }
 82 
 83     ifs.close();
 84 }
 85 
 86 int main(int argc, char *argv[])
 87 {
 88     readFile1();
 89     readFile2();
 90     readFile3();
 91     readFile4();
 92 
 93     return 0;
 94 }
 95 
 96 
 97 /*
 98 总结:
 99 
100 文件test.txt的内容如下:
101 23 Robot    ZhuHai 501   #27 12/ GuangZhou !!! 31...
102 
103 程序输出如下:
104 23RobotZhuHai501#2712/GuangZhou!!!31...
105 23 Robot        ZhuHai 501   #27 12/ GuangZhou !!! 31...
106 23RobotZhuHai501#2712/GuangZhou!!!31...
107 23 Robot        ZhuHai 501   #27 12/ GuangZhou !!! 31...
108 */

原文链接: https://www.cnblogs.com/Robotke1/archive/2013/04/23/3037855.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/85645

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月9日 下午10:10
下一篇 2023年2月9日 下午10:10

相关推荐