我编写了一个程序,它包含 n 个文件,然后用户将输入他们的文件名,然后我的程序会将所有这些文件连接成一个由换行符分隔的文件,这是我的程序(有效好的):
#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 Line
是 \r\n
但对于基于 UNIX 的平台它只是 \n
。因此,当我们以二进制模式读取时,字符将按原样读取。但如果您以非二进制模式阅读它,则字符将根据需要进行修改。
要以二进制模式打开文件,请使用 ios::binary
标志。
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary);
关于c++ - 使用二进制读写连接文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49056983/