简体   繁体   English

c++ - 如何在C++中将n行从一个文件替换到另一个文件?

[英]How can I replace n lines from a file to another file in C++?

I want to replace the last n lines of first.txt with the first n lines of second.txt where n is input by the user.我想用 second.txt 的前 n 行替换 first.txt 的最后 n 行,其中 n 由用户输入。 Here's my code:这是我的代码:

ofstream myFirst("first.txt", ios:: binary);
ifstream mySecond("second.txt", ios::binary);
int firstFileLine = lineCountFirst;
int count = 0;
while(getline(myFirst, line)){
    count++;
    if(count >= firstFileLine){
        getline(mySecond, line2); // I don't know if it can be written like this
        line = line2;            // here to replace line to line2
    }
}
myFirst.close();
mySecond.close();

The two lines of code with comments are where I am confused about.带注释的两行代码是我感到困惑的地方。 Any ideas about how to replace the file?关于如何替换文件的任何想法?

I want to replace the last n lines of first.txt with the first n lines of second.txt where n is input by the user.我想用 second.txt 的前 n 行替换 first.txt 的最后 n 行,其中 n 由用户输入。

Read first.txt in a std::vector<std::string> line by line. first.txt读取std::vector<std::string> first.txt Remove the last n elements from the vector.从向量中删除最后n元素。 Write the elements of the vector to a temporary file.将向量的元素写入临时文件。 Read n lines from second.txt and append them to the temporary file.second.txt读取n行并将它们附加到临时文件中。 Unlink first.txt and rename the temporary file you created.取消first.txt并重命名您创建的临时文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM