簡體   English   中英

C ++將文件的一部分復制到新文件

[英]C++ copying parts of a file to a new file

我正在嘗試使用來自兩個不同現有文件的數據創建一個新文件。 我需要完整地復制第一個現有文件,這已成功完成。 對於第二個現有文件,我只需要復制最后兩列,並將其附加到每行末尾的第一個文件中。

例如:

來自第一個文件的信息已復制到我的新文件中:

20424297 1092 CSCI 13500 B 3

20424297 1092 CSCI 13600 A- 3.7

現在,我需要復制此文件中每行的最后兩列,然后將它們附加到上面文件中的相應行:

17250 3.00 RNL

17381 3.00 RLA

即我需要在第一行的末尾附加“ 3.00”和“ 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循環將每一行分配給一個變量,但是我無法使其正常工作。

我已經想到的另一種方法是從第二個文件中刪除所有整數,因為我只需要最后兩列,並且這些列都不包含整數。

如果您看一下文件流的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.

這個非常相似的問題提供了更好的代碼

另一種可能性就是簡單地事先查找文件中有多少行。 (速度較慢,但​​可行),在這種情況下,只需循環調用getline的文件並遞增count變量,將其重置為開始,然后重復直到達到count - 2 雖然我自己不會使用這種技術。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM