使用 Read() 和 Write() 函数连接 2 个文件

Using Read() and Write() Functions to Concatenate 2 Files

我目前正在学习如何使用 read() 和 write() 函数来实现一个连接文件的程序。

我将一个名为 "NotesBetweenTwoSisters2.txt" 的文本文件连接到另一个名为 "NotesBetweenTwoSisters1.txt." 的文本文件的末尾(因此现在 NotesBetweenTwoSisters1.txt 的文件大小更大。)

"NotesBetweenTwoSisters1.txt"

Madam, 

Keep an eye on the radar. If it doesn't look that good for kayak paddling tonight, then the next time which we can rent the kayak is tomorrow noon. 
But at that time you will have to take care of the pup, and only your darling and I can enjoy the trip. 

Sis

"NotesBetweenTwoSisters2.txt"


Hi sis,

I only deal with loyal ones. Obviously the pup is much more loyal. You and I really see eye to eye on this issue. Enjoy your kayak paddling.

"Your Madam"

我已经编写了让两个文件内容都按预期输出到终端的代码,但我不确定我是否正确地进行了连接。如果有人能帮助我了解如何正确使用 read() 和 write() 函数将文件连接在一起,我将不胜感激!

当前程序代码

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

int main()
{
    fstream inFile1;
    fstream inFile2;
    fstream outFile;

    inFile1.open("NotesBetweenTwoSisters1.txt", ios::in|ios::binary);
    inFile2.open("NotesBetweenTwoSisters2.txt", ios::in|ios::binary);

    inFile1.seekg(0, inFile1.end);
    int size1 = inFile1.tellg();
    inFile1.seekg(0, inFile1.beg);

    // cout << "File #1 Size: " << size1 << endl;
    char arr1[size1];

    inFile1.read(arr1, sizeof(arr1));
    inFile1.close();

    inFile2.seekg(0, inFile2.end);
    int size2 = inFile2.tellg();
    inFile2.seekg(0, inFile2.beg);

    // cout << "File #2 Size: " << size2 << endl;
    char arr2[size2];

    inFile2.read(arr2, sizeof(arr2));
    inFile2.close();

    outFile.open("outputFile.dat", ios::out|ios::app|ios::binary);
    outFile.write(arr1, sizeof(arr1));
    outFile.write(arr2, sizeof(arr2));

    for(int count = 0; count < size1; count++)
    {
        cout << arr1[count] << "";
    }

    for(int count = 0; count < size2; count++)
    {
        cout << arr2[count] << "";
    }

    cout << endl;
    outFile.close();

    return 0;
}

当前输出

Madam,

Keep an eye on the radar. If it doesn't look that good for kayak paddling tonight, then the next time which we can rent the kayak is tomorrow noon.
But at that time you will have to take care of the pup, and only your darling and I can enjoy the trip.

Sis
Hi sis,

I only deal with loyal ones. Obviously the pup is much more loyal. You and I really see eye to eye on this issue. Enjoy your kayak paddling.

"Your Madam"

首先,您需要使用vector,否则您必须在语法上正确定义动态数组。这是在 C++ 中定义动态数组的方式:

char *arr1 = new char[size1]
char *arr2 = new char[size2]

因为 size1size2 不是常量,将在 运行 时间内初始化,你不能像这样声明动态数组 char arr1[size1] 你需要指向一个将如上声明的数组。您也可以阅读更多相关信息 here。 那么你的 write 函数将按预期工作,并将你的两个数组附加到一个名为 outfile.

的二进制文件中