[英]c++ how to copy specific lines from a file to another?
I want to write a program that will copy a few lines in a file in another file. 我想编写一个程序,将一个文件中的几行复制到另一个文件中。 for example copy line 5 to 100 from file a and write it to file b.
例如,将文件5的第5行复制到100,然后将其写入文件b。 thanks
谢谢
this is my code.but my code copying all content of file a to file 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;
}
Here is another way to do it: 这是另一种方法:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.