使用二进制读取和写入连接文件

Concatenate files using the binary read and write

本文关键字:连接 文件 二进制 读取      更新时间:2023-10-16

我编写了一个程序,该程序需要n个文件,然后用户将输入他们的文件名,然后我的程序会将所有这些文件连接成1个由换行符分隔的文件,这是我的程序(工作正常):

#include <iostream>
#include <string>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
int main()
{
int n;
cin>>n;
ifstream read;
ofstream finalout;
int i;
finalout.open("concatn.txt");
if(!finalout)
{
cout << "Oops something went wrong, SORRY DUDE" << endl;
}
char a[n][50];
char help[50];
for(i=0; i<n; i++)
{
scanf("%s", help);
strcpy(a[i], help);
}
string STRING;
for(i=0; i<n; i++)
{
read.open(a[i]);
if(read == NULL)
{
cout << "Could not open the file, SORRY DUDE" << endl;
}
while(read.eof() == 0)
{
getline(read, STRING);
finalout << STRING;
}
finalout << "n";
read.close();
read.clear();
}
finalout.close();
return 0;
}

现在我必须做同样的事情,但使用"二进制读写",但我的输出文件应该仍然是 txt 文件,我该怎么做,有人可以解释这到底是什么意思,因为我有点困惑!?

二进制读写只是为了支持plateform-independent读写支持。例如,在Windows平台上New Linern,但对于基于UNIX的平台,它只是n。因此,当我们以二进制模式读取时,字符将按原样读取。但是,如果您在非二进制模式下读取它,那么如果需要,字符将被修改。

要在二进制模式下打开文件,请使用ios::binary标志。

ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);

更多信息请看这里