[英]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
)。
更多在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.