用 C++ 编写二进制文件

writting a binary in c++

所以我有这个程序可以读取任何文件(例如图像、txt)并获取其数据并使用相同的数据创建一个新文件。问题是我想要数组中的数据而不是向量中的数据,当我将相同的数据复制到 char 数组时,每当我尝试将这些位写入文件时,它都无法正确写入文件。

所以问题是如何从 std::ifstream input( "hello.txt", std::ios::binary ); 获取数据并将其保存到 char array[] 以便我可以将该数据写入新文件?

节目:

#include <stdlib.h>
#include <string.h>
#include <fstream>
#include <iterator>
#include <vector>
#include <iostream>
#include <algorithm>

int main()
{
    FILE *newfile;
    std::ifstream input( "hello.txt", std::ios::binary );
    
    std::vector<unsigned char> buffer(std::istreambuf_iterator<char>(input), {});
        
    char arr[buffer.size()];
    std::copy(buffer.begin(), buffer.end(), arr);

    int sdfd;
    sdfd = open("newhello.txt",O_WRONLY | O_CREAT);
    write(sdfd,arr,strlen(arr)*sizeof(char));
    close(sdfd);

   return(0);
}

试试这个:
(它基本上使用一个char*,但这里是一个数组。在这种情况下你可能不能在堆栈中有一个数组)

#include <iostream>
#include <fstream>

int main() {
    std::ifstream input("hello.txt", std::ios::binary);
    char* buffer;
    size_t len;  // if u don't want to delete the buffer
    if (input) {
        input.seekg(0, input.end);
        len = input.tellg();
        input.seekg(0, input.beg);

        buffer = new char[len];

        input.read(buffer, len);
        input.close();

        std::ofstream fileOut("newhello.txt");
        fileOut.write(buffer, len);
        fileOut.close();

        // delete[] buffer; u may delete the buffer or keep it for further use anywhere else
    }
}

这应该可以解决您的问题,如果您不想删除它,请记住始终保留缓冲区的长度(此处为len)。
更多here