c++ - 使用二进制读写连接文件

标签 c++ c++11

我编写了一个程序,它包含 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);

参见 here for more info

关于c++ - 使用二进制读写连接文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49056983/

相关文章:

c++ - 在 C++ 中使用 atof 将字符串转换为十进制不起作用

c++ - Lambda 函数作为构造函数中 std::function 的默认参数

c++ - int to short 分配失败

c++ - 类内枚举

c++ - 将无状态 C++ 函数从里到外转换为有状态函数

c++ - 如何在MFC 的CScrollView 类中制作不可见的滚动条?

c++ - 具有多个模板参数包的部分模板特化

c++ - 如果 child 不需要父类的所有 protected 成员,这是不是糟糕的类设计?

c++ - "++l *= m"是未定义的行为吗?

c++ - 为什么 std::map 没有 insert(key &, value & v) 类型的插入函数