简体   繁体   English

如何读取包含'\\ 0'字符的文件?

[英]How to read a file containing '\0' characters?

I wrote a simple program to read a TXT file. 我编写了一个简单的程序来读取TXT文件。 The problem is the file contains some '\\0' characters. 问题是文件包含一些'\\ 0'字符。 Here's a sample : 这是一个示例:

在此处输入图片说明

And here's the solution I've found to solve my problem : 这是我找到的解决问题的方法:

FILE *pInput = fopen("Encoded.txt", "rb");

    fseek(pInput, 0, SEEK_END);
    size_t size = ftell(pInput);
    fseek(pInput, 0, SEEK_SET);

    char *buffer = new char[size];

    for (int i = 0; i < size; i++)
        buffer[i] = fgetc(pInput);

I would like to replace the following code : 我想替换以下代码:

for (int i = 0; i < size; i++)
        buffer[i] = fgetc(pInput);

By just a simple function call. 通过一个简单的函数调用。 Is there a function which can do this job ? 有功能可以完成这项工作吗? I tried with fread, fgets but they stop to read at the first '\\0' character. 我尝试使用fread,fgets,但它们在第一个'\\ 0'字符处停止读取。

Thanks a lot in advance for your help. 在此先感谢您的帮助。

fread is fine for reading arbitrary binary; fread适用于读取任意二进制文件; it returns the number of elements read, which is a value you should store and use in all dealings with your buffer. 它返回读取的元素数,这是您在处理缓冲区时应存储并使用的值。 (Read some documentation on fread to find out how it works.) (请阅读有关fread一些文档以了解其工作原理。)

(On the other hand, with fgets you won't be able to find out how many characters were read because a pointer to a [assumedly null-terminated] C-string is all you get out of it.) (另一方面,使用fgets您将无法找出读取了多少个字符,因为您只能从中获得指向[假定为以空值终止的] C字符串的指针。)

You need to ensure that your handling of your resultant buffer is zero-safe. 您需要确保对结果缓冲区的处理是零安全的。 That means no strlen or the like, which are all designed to work on ASCII input (more or less). 这意味着没有任何strlen之类的东西,它们都被设计为可以在ASCII输入上工作(或多或少)。

Quoting cplusplus.com and removing the plumbering that you'll find in the link: 引用cplusplus.com并删除您在链接中找到的水管工:

  // Open the file with the pointer at the end
  ifstream file("example.bin", ios::in|ios::binary|ios::ate); 

  // Get the file size
  streampos size = file.tellg();

  // Allocate a block
  char* memblock = new char [size];

  // We were at the end go to the begining
  file.seekg 0, ios::beg);

  // Read the whole file
  file.read(memblock, size);

Et voilà ! 等等!

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

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