我怀疑我甚至没有使用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。
_________________________________________________________________________________
问题是:我是否正确地创建了文件,为什么我没有看到二进制数据被写入?
发布于 2013-04-15 20:27:31
你确实正确地创建了文件。你误解了有两种类型的文件,二进制和文本。相反,有两种I/O操作:文本(如operator<< )和二进制(如write )。
您没有看到两个字节字符的原因是std::string只有一个字节字符。如果您想要两个字节字符,请使用std::wstring。
https://stackoverflow.com/questions/16024071
复制相似问题