c ++如何将特定行从文件复制到另一个文件?

时间:2014-10-03 01:40:34

标签: c++

我想编写一个程序,将一个文件中的几行复制到另一个文件中。例如,从文件a复制第5行到第100行并将其写入文件b。感谢

这是我的代码。但我的代码将文件a的所有内容复制到文件b。

#include <iostream>
#include <fstream>
using namespace std;

int main(){
   char line[100];

   ifstream is("a.txt");
   ofstream os("b.txt");

   if (is.is_open()){
      while (!is.eof()){
         is.getline(line,100,'\n');
         os << line << endl;
         }
   }
   else{
      cout << "a.txt couldn't be opened. Creat and write something in a.txt, and try again." << endl;
   }

   return 0;
}

1 个答案:

答案 0 :(得分:2)

这是另一种方法:

 std::ofstream outFile("/path/to/outfile.txt");
 std::string line;

 std::ifstream inFile("/path/to/infile.txt");
 int count = 0;
 while(getline(inFile, line)){

     if(count > 5 && count < 100){
        outFile << line << std::endl;
     }
     count++;
 }
 outFile.close();
 inFile.close();