Home > database >  writting a binary in c
writting a binary in c

Time:12-29

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);
}

CodePudding user response:

Try this:
(It basically uses a char*, but it's an array here. You probably can't have an array in the stack in this case)

#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
    }
}

This should probably solve your problem, remember to always have the length (len here) of the buffer if you don't want to delete it.
More here

  • Related