【问题标题】:writting a binary in c++用 C++ 编写二进制文件
【发布时间】:2021-12-28 15:18:23
【问题描述】:

所以我有这个程序可以读取任何文件(例如图像、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 数组的 tcp 服务器
  • buffer.data() 为您提供了一个 unsigned char* 指向该向量管理的数组的指针,您可以将其传递给您现在将 arr 传递给的任何函数。
  • strlen(arr) 不会返回与buffer.size() 相同的值。它返回第一个 0(零)字节的偏移量,如果没有,则显示未定义的行为。 strlen 仅在处理以 nul 结尾的文本字符串时才有意义;不适用于二进制数据。
  • 读取文件时使用 C++ API ifstream 看起来很奇怪,而编写时使用低级的、仅 Unix 的 C 接口 open

标签: c++ file


【解决方案1】:

试试这个:
(它基本上使用了一个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

【讨论】:

  • 尽管这是 OP 要求的,但我不推荐这种方式。手动管理内存很容易出错。在最坏的情况下,我会使用 std::unique_ptr 及其数组重载
猜你喜欢
  • 2015-11-29
  • 2017-10-20
  • 2019-03-27
  • 1970-01-01
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多