C++中可以采用stream读取文本文件,基本方式是一次一行,编程简洁易行,比用C方便多了。但是,凡事有利有弊,当文件行数较多时,文件读取IO次数就会随之增加,文件读取的时间会急剧增长。因为文件IO的时间要远大于CPU在内存中处理数据的时间,假如IO时间是毫秒级的,那么CPU在内存处理数据是纳秒级的。
很显然,C++中文本文件读取优化要解决的基本问题之一就是减少IO次数,最常用的方法之一是缓冲,也就是一次性将数据会部读入内存之后再处理。例如:
1. C++文本文件读写程序(基本方式)
- //C++ code:
- #include <iostream>
- #include <fstream>
- #include <string>
- using namespace std;
- class file{
- public:
- //按行读数据,不分行写入另外一个文件
- bool fromShortToLong(string s_path,string d_path){
- string buffer;
- fstream infile(s_path);
- fstream outfile(d_path);
- if(!infile){
- cout << "Unable to open infile";
- exit(1); // terminate with error
- }
- if(!outfile){
- cout << "Unable to open outfile";
- exit(1); // terminate with error
- }do{
- outfile<<buffer;
- }while (getline(infile,buffer));
- cout<<"读写完成。"<<endl;
- system("pause");
- outfile.close();
- infile.close();
- }
- };
- void main(){
- file test;
- test.fromShortToLong("D://test_read.txt","D://test_write.txt");
- }
2. 使用缓冲的读写程序
- bool fromShortToLong(string s_path,string d_path)
- {
- string buffer;
- ifstream infile(s_path.c_str());
- ofstream outfile(d_path.c_str());
- if(!infile)
- {
- cout << "Unable to open infile";
- exit(1); // terminate with error
- }
- if(!outfile)
- {
- cout << "Unable to open outfile";
- exit(1); // terminate with error
- }
- buffer.assign(istreambuf_iterator<char>(infile),istreambuf_iterator<char>());
- stringstream strStr;
- strStr.str(buffer);
- string linestr;
- do
- {
- outfile<<linestr;
- }
- while (getline(strStr,linestr));
- cout<<"读写完成。"<<endl;
- return true;
- }
后者比前者的读写速度要快很多倍。主要原因就是后者的文件IO次数远远少于前者。
3. Java中的缓冲应用
其实缓冲在各种语言中都广泛用到,目的不外乎加快数据读写速度,下面是Java中的文本文件读写程序:
- //java code
- import java.io.BufferedReader;
- import java.io.File;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- public class Txt {
- //按行读数据,不分行写入另外一个文件
- public Boolean fromShortToLong(String s_path,String d_path) throws IOException {
- Boolean scc=false;
- File file = new File(s_path);
- FileWriter fw=new FileWriter(d_path);
- try {
- BufferedReader bw = new BufferedReader(new FileReader(file));
- String line = null;
- while((line = bw.readLine()) != null){
- fw.write(line);
- }bw.close();
- fw.close();
- scc=true;
- } catch (IOException e) {
- scc=false;
- e.printStackTrace();
- }
- return scc;
- }
- }
4. 备注
上文中的示例不考虑文本读取后对文本行的处理,其实只是一个简单的复制程序。如果仅仅复制文本文件的话,也可以这样:
- #define BUF_SIZE 1024
- std::ifstream ifs("c://test_read.txt");
- std::ofstream ofs("c://test_write.txt");
- if (ifs.is_open())
- {
- char buf[BUF_SIZE] = {0};
- while(!ifs.read(buf, BUF_SIZE).eof())
- {
- ofs.write(buff, BUF_SIZE - 1);
- }
- }
还可以这样:
- void copy(const string& strInFile, const string& strOutFile)
- {
- ifstream ifs(strInFile.c_str());
- ofstream ofs(strOutFile.c_str());
- copy(istream_iterator<char>(ifs),istream_iterator<char>(), ostreambuf_iterator<char>(ofs));
- }
5154

被折叠的 条评论
为什么被折叠?



