首页 文章

std :: fstream :: write && std :: fstream :: putc std :: ios :: binary

提问于
浏览
0

我怀疑我甚至没有使用 std::fstream 为二进制I / O创建和打开文件

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

}

我相信这是真的,因为我正在写数据

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

但该文件是具有可读文本数据的标准文本文件 . 我想以二进制格式(2字节字符)写一个字符串或字符本身的字符 . 我试图操作 std::fstream 类似于RandomAccessFile .

_________________________________________________________________________________

问题是:我是否正确创建了文件,为什么我没有看到写入的二进制数据?

1 回答

  • 0

    你确实正确地创建了文件 . 你有一个误解,有两种文件,二进制和文本 . 相反,有两种I / O操作,如 operator<< 和像 write 这样的二进制文本 .

    您没有看到两个字节字符的原因是 std::string 只有一个字节字符 . 如果你想要两个字节的字符使用 std::wstring .

相关问题