【发布时间】:2013-04-15 20:21:53
【问题描述】:
我怀疑我什至没有使用 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字节字符)编写字符串的字符或字符本身。我正在尝试操作类似于RandomAccessFile 的std::fstream。
_____________ __________________ _________________ _________________________________
问题是:我是否正确创建了文件,为什么我没有看到写入的二进制数据?
【问题讨论】:
-
我相信你需要使用
binary_search_file.open(data_file_name.c_str(), std::ios::binary)。注意c_str()。 -
@Thomas:(a) Visual Studio 提供了一个重载来支持 OP 的代码; (b) C++11 也是如此; (c) 如果没有,那将导致编译错误,并且很明显 OP 没有遇到编译错误。