C ++将文件的一部分复制到新文件

时间:2016-02-29 02:29:27

标签: c++ file append file-handling

我正在尝试使用来自两个不同现有文件的数据创建一个新文件。我需要复制其中的第一个现有文件,这是我成功完成的。对于第二个现有文件,我只需要复制最后两列,并将其附加到每行末尾的第一个文件中。

例如:

第一个文件的信息已经复制到我的新文件中:

20424297 1092 CSCI 13500 B 3

20424297 1092 CSCI 13600 A- 3.7

现在我需要复制此文件中每行的最后两列,然后将它们附加到上面文件中的相应行:

17 250 3.00 RNL

17 381 3.00 RLA

即。我需要" 3.00"和#34; RNL"附加到第一行的末尾," 3.0"和" RLA"附加到第二行的末尾等。

这是我到目前为止所做的:

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <cstdlib>
using namespace std;

int main() {

    //Creates new file and StudentData.tsv
    ofstream myFile;
    ifstream studentData;
    ifstream hunterCourseData;

    //StudentData.tsv is opened and checked to make sure it didn't fail
    studentData.open("StudentData.tsv");
    if(studentData.fail()){

       cout << "Student data file failed to open" << endl;
       exit(1);
    }


    //My new file is opened and checked to make sure it didn't fail
    myFile.open("file.txt");
    if(myFile.fail()){

        cout << "MyFile file failed to open" << endl;
        exit(1);

    }

    //HunterCourse file is opened and checked to make sure if didn't   fail
    hunterCourseData.open("HunterCourse.tsv");
    if(myFile.fail()){

        cout << "Hunter data file failed to open" << endl;
        exit(1);
    }

    // Copies data from StudentData.tsv to myFile
    char next = '\0';
    int n = 1;

        while(! studentData.eof()){

        myFile << next;
        if(next == '\n'){

            n++;
            myFile << n << ' ';

        }
        studentData.get(next);

    }


    return 0;
}

我要去尝试解决这个问题的香蕉。我确定这是一个简单的解决办法,但我找不到任何有效的在线信息。我已经研究过使用ostream和while循环将每一行分配到一个变量中但是我无法使其工作。

我想到的另一种方法是从第二个文件中删除所有整数,因为我只需要最后两列,而且这些列都不包含整数。

1 个答案:

答案 0 :(得分:0)

如果您查看文件流的the seekg方法,您会注意到第二个版本允许您实现位置以设置偏移量(例如ios_base::end设置与文件末尾相比的偏移量。通过这种方式,您可以有效地从文件末尾向后读取。 请考虑以下

int Pos=0;
while(hunterCourseData.peek()!= '\n')
{
    Pos--;
    hunterCourseData.seekg(Pos, ios_base::end);
}
//this line will execute when you have found the first newline-character from the end of the file.

Very Similar question

提供了更好的代码

另一种可能性就是预先找到文件中有多少行。 (不太快,但可行),在这种情况下,只需循环调用getline的文件并递增计数变量,重置为开始,然后重复直到达到count - 2。虽然我自己也不会使用这种技术。