简体   繁体   English

使用fread()读入char *缓冲区

[英]using fread() to read into a char * buffer

I've been working on a compression program for text files that uses a trie and custom bitstrings for each character. 我一直在研究文本文件的压缩程序,该程序使用trie和每个字符的自定义位串。 The file I'm reading from was written using fwrite(name, wb) , and I have looked over the file (in binary mode) and I have verified that the bits are correct to what they should have been written. 我正在读取的文件是使用fwrite(name, wb)编写的,并且我已经查看了该文件(以二进制模式),并且我已验证这些位与应写入的内容正确。 The problem I am having is reading this binary file back into a file that can be read. 我遇到的问题是将此二进制文件读回到可以读取的文件中。

void read2(string fname, ofstream &outf)
{
    fname += ".mcp";
    outf << endl;
    std::ifstream inf(fname, std::ios::binary);
    std::vector<char> data{
    std::istreambuf_iterator<char>(inf),
    std::istreambuf_iterator<char>() };
    std::cout << "Size: " << data.size() << '\n';
    std::copy(data.begin(), data.end(), std::ostreambuf_iterator<char>(outf));
}

The output for this function (cout) is as follows: 该函数(cout)的输出如下:

Size: 25 

(using a smaller test file) (使用较小的测试文件)

The ofstream output should read: 10001110 00000100 01001001 10110001 10011001 00101011 01101000 10010101 01000101 01010001 01111010 01101001 10100110 01000000 01111010 00010111 00000110 10101000 11100000 01000101 11011100 11110011 10010111 10001011 00000000 This is the binary form of the numbers that were read: (sorry its reading it as hex code, I copied it straight from the output file) ofstream输出应为:10001110 00000100 01001001 10110001 10011001 00101011 01101000 10010101 01000101 01010001 01111010 01101001 10100110 01000000 01111010 00010111 00000110 10101000 11100000 01000101 11011100 11110011 10010111 10001011 00000000这是读取的数字的二进制形式:(sor代码,我直接从输出文件中复制了它)

c5 bd 04 49 c2 b1 e2 84 a2 2b 68 e2 80 a2 45 51 7a 69 c2 a6 40 7a 17 06 c2 a8 c3 a0 45 c3 9c c3
b3 e2 80 94 e2 80 b9 20  

I used the hex editor plugin for notepad++ to view the bits. 我使用了记事本++的十六进制编辑器插件来查看这些位。

The answer to the question was actually very simple, the ofstream object, outf that I was using to output data to was not opened in binary mode, so I just created a new object in binary mode and output to it and it worked. 这个问题的答案实际上非常简单,我用于输出数据的ofstream对象outf并不是在二进制模式下打开的,因此我只是在二进制模式下创建了一个新对象并将其输出并正常工作。

void read2(string fname, ofstream &outf)
{
    string fname1 =fname+ ".mcp", outfile="binarycheck";
    std::ifstream inf(fname1, std::ios::binary);
    std::ofstream ouf("binarycheck.txt", std::ios::binary);
    std::vector<unsigned char> data{
    std::istreambuf_iterator<char>(inf),
    std::istreambuf_iterator<char>() };
    std::cout << "Size: " << data.size() << '\n';
    std::copy(data.begin(), data.end(), std::ostreambuf_iterator<char>(ouf));
}

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

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