lundi 23 décembre 2019

C++ write and read a file in binary mode

I want to create a binary file in /dev/shm/uploaded and open a file in binary mode and write data into it.

    std::string string_path = "/dev/shm/uploaded/";
    std::string filename = "download_file.out";
    std::string tmpStr = "The quick brown fox jumps over the lazy dog";

    createFile(string_path, filename); 

    bool createFile(std::string &string_path, std::string &filename) {
        std::string command_string = "mkdir -p ";
        command_string.append(string_path);
        std::cout << command_string << std::endl;
        int check = system(command_string.c_str());
        if(-1 == check) {
           return false;
        }
        std::ofstream outfile(string_path + filename, std::ios::binary | std::ios::out);
        if(outfile.is_open()) {
          for (int i = 0; i < 100000; i++) {
              outfile << tmpStr;
          }
        }
        outfile.close();
        return true;
    }

I suspect that using << operator I am writing the data in text mode, rather than in binary mode. I want to write the data in binary mode.

I was looking at binary read and write

It has a function as follows

template<>
std::ostream& binary_write_string(std::ofstream& stream, const std::string& value){
    return stream->write(value.c_str(), value.length());
}

In this function what does a templated function without typename or class mean? Is this the correct approach.

Aucun commentaire:

Enregistrer un commentaire