Question

I wrote a simple program to read a TXT file. The problem is the file contains some '\0' characters. Here's a sample :

enter image description here

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.

Thanks a lot in advance for your help.

Was it helpful?

Solution

fread is fine for reading arbitrary binary; 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.)

(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.)

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).

OTHER TIPS

Quoting cplusplus.com and removing the plumbering that you'll find in the link:

  // 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à !

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top