【发布时间】:2019-12-23 08:04:22
【问题描述】:
我想在/dev/shm/uploaded中创建一个二进制文件,并以二进制模式打开一个文件并写入数据。
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;
}
我怀疑使用<< 运算符我正在以文本模式而不是二进制模式写入数据。
我想以二进制模式写入数据。
它的作用如下
template<>
std::ostream& binary_write_string(std::ofstream& stream, const std::string& value){
return stream->write(value.c_str(), value.length());
}
在这个函数中,没有typename 或class 的模板函数是什么意思?这是正确的方法吗。
【问题讨论】:
-
In this function what does a templated function without typename or class mean?- 这是一个template specialization -
文本和二进制模式的主要区别不就是换行吗?
-
一个字符串代表一个文本,不管你是否写成二进制模式。它仍然会显示为人类可读的文本。如果您想查看差异,请尝试写一个数字。
-
binary_write_string应该是binary_write,前者不会编译,因为它是一个不存在的函数的特化 -
@Azad 这实际上不是真的。这取决于编码和字节序,这会导致二进制和文本模式之间的不同输出。