C++将文件的某些部分复制到新文件中

C++将文件的某些部分复制到新文件中

问题描述:

我试图用两个不同的现有文件中的数据创建一个新文件。我需要完整地复制第一个现有文件,这是我成功完成的。对于第二个现有文件,我需要复制最后两列,并将其附加到每行末尾的第一个文件。C++将文件的某些部分复制到新文件中

例:

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

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”和“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

1.看起来你会得到第二个文件的最后'列'; 2.你真的需要使用C++吗?如果你在Linux上,你可以使用很多的utils来实现这个目标,例如'awk'。 – Mine

+0

听起来像要复制最后两列,而不是最后两行。这些行是各种各样的东西,这些列是令人厌恶的东西。 – Galik

+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

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