So i have this program that supposedly reads any file (e.g images, txt) and get its data and creates a new file with that same data. The problem is that i want the data in an array and not in a vector and when i copy that same data to char array, whenever i try to write those bits into a file it doesnt write the file properly.
So the question is how can i get the data from std::ifstream input( "hello.txt", std::ios::binary ); and save it an char array[] so that i can write that data into a new file?
Program:
#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); }
buffer.data()gives you anunsigned char*pointer to the array managed by the vector, that you can pass to whatever function you are now passingarrto.strlen(arr)doesn't return the same value asbuffer.size(). It returns the offset of the first 0 (zero) byte, or exhibits undefined behavior if there is none such.strlenonly makes sense when working with nul-terminated text strings; not for binary data.ifstream, while to write you use the low-level, Unix only, C interfaceopen.