0
votes

I suspect I am not even creating and opening a file for binary I/O using std::fstream

BinarySearchFile::BinarySearchFile(std::string file_name){

    // concatenate extension to fileName
    file_name += ".dat";

    // form complete table data filename
    data_file_name = file_name;

    // create or reopen table data file for reading and writing
    binary_search_file.open(data_file_name, std::ios::binary);  // create file

    if(!binary_search_file.is_open()){

        binary_search_file.clear();
        binary_search_file.open(data_file_name, std::ios::out | std::ios::binary);
        binary_search_file.close();
        binary_search_file.open(data_file_name), std::ios::out | std::ios::in | std::ios::binary | std::ios::ate;
    }

   try{
       if(binary_search_file.fail()){
            throw CustomException("Unspecified table data file error");
       }
   }
   catch (CustomException &custom_exception){  // Using custom exception class
       std::cout << custom_exception.what() << std::endl;
       return;
   }    

}

I believe this is true because I am writing data

void BinarySearchFile::writeT(std::string attribute){
    try{
        if(binary_search_file){
             binary_search_file.write(attribute.c_str(), attribute.length());
        }else if(binary_search_file.fail()){
             throw CustomException("Attempt to write attribute error");
        }

    }
    catch(CustomException &custom_exception){  // Using custom exception class
        std::cout << custom_exception.what() << std::endl;
        return;
    }
}

But the file is a standard text file with readable text data. I want to write the characters of a string or characters themselves in binary format (2 byte char). I am attempting to operate a std::fstream similar to a RandomAccessFile.

_________________________________________________________________________________

Question is: Did I create the file correctly and why am I not seeing binary data written?

1
I believe you need to use binary_search_file.open(data_file_name.c_str(), std::ios::binary). Note the c_str(). - Thomas Matthews
@Thomas: (a) Visual Studio provides an overload to support the OP's code; (b) so does C++11; (c) if it didn't, that would cause a compilation error, and it seems clear that the OP is not experiencing a compilation error. - Lightness Races in Orbit

1 Answers

0
votes

You did create the file correctly. You have a misunderstanding that there are two kinds of files, binary and text. Instead there are two kinds of I/O operations, text like operator<< and binary like write.

The reason that you aren't seeing two byte chars is that std::string only has one byte chars. If you want two byte chars use std::wstring.