繁体   English   中英

C++ 以二进制方式写入和读取文件

[英]C++ write and read a file in binary mode

我想在/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());
}

在这个函数中,没有typenameclass的模板化函数是什么意思? 这是正确的方法。

正如 Botje 所建议的,文本模式和二进制模式之间的主要区别在于换行符转换。 您可以尝试以下代码并查看输出。

#include <fstream>

using namespace std;

int main()
{
    string tmpStr = "The quick brown fox jumps over the lazy dog\n";

    ofstream outbinfile("output_binary.txt", std::ios::binary | std::ios::out);
    for (int i=0; i<3; i++)
        outbinfile << tmpStr;
    outbinfile.close();

    ofstream outfile("output.txt", std::ios::out);
    for (int i=0; i<3; i++)
        outfile << tmpStr;
    outfile.close();

    return 0;
}

正如预期的那样, output_binary.txt是 132 字节。 但是output.txt在 Windows 中是 135 个字节。 因为对于换行符,它实际上写出了\\r\\n [1]

  1. xfstream( fn, ios::text )xfstream( fn, ios::binary ) (其中 x 是io )之间的区别在于如何插入/提取行尾
    • 对于文本流is << '\\n'将插入(取决于操作系统) \\n\\r 提取时,序列将被转换回\\n
    • 对于二进制流,您插入/提取的内容就是您写入/读取的内容
  2. 以二进制模式打开流和向其中写入/读取二进制数据是不同的事情。 当您使用插入/提取运算符( << & >> )时,您写入/读取格式化数据(类似于 c 中的printf

     #include <iostream> #include <iomanip> using namespace std; //... cout << setfill( '~' ) << setw( 2 ) << 2; // outputs "~2"
  3. 如果要写入/读取实际字节(例如,32 位整数的 4 个字节,而不是其人类可读形式),则必须使用ostream::write / istream::read c++ 不会阻止您在文本流中使用这些函数。 您有责任正确组合它们。

  4. 在 c++ 中,模板函数可能是专门的:对特定模板签名表现出不同的行为。 您从引用的链接中错过的是该函数的非专业版本

     template<typename T> void f( T ) { cout << "unspecialized\\n"; } template<> void f( const char* s ) { cout << "specialized\\n"; } //... f( 0 ); // prints "unspecialized" f( 'c' ); // prints "unspecialized" f( "" ); // prints "specialized"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM