Home > Back-end >  C reading a file which contains nulls
C reading a file which contains nulls

Time:03-01

I'm reading a file a RSA encrypted binary file which contains nulls. The file is encrypted and saved in python, then read in c .

Python treats it fine, reading and writing it just displays the nulls as

...\x94\x00\xbf...

However, in my C it terminates it early.


FILE* fpy = fopen("test.txt", "rb");
unsigned char* signPy = (unsigned char*)malloc(256);
fread(signPy, 1, 256, fpy);
fclose(fpy);
cout << signPy << endl;

The file is exactly 256 bytes so I know I'm allocating enough memory. Using fread it terminates at the first null. Any help would be appreciated.

CodePudding user response:

Continuing the code:

FILE* fpy = fopen("test.txt", "rb");
unsigned char* signPy = (unsigned char*)malloc(256);
int const count = fread(signPy, 1, 256, fpy);
fclose(fpy);
// cout << signPy << endl;
for (int i = 0; i < count;   i)
  putchar(signPy[i]);

Problem was that cout will treat signPy as null terminated char buffer, so it will stop printing more characters once null is encountered.

You can print the data in binary format as well, as suggested in comments.

CodePudding user response:

Not really an answer to your actual problem, but since this is C , here’s how to do it in C :

std::string signPy( 256, '\0' );
{
  std::ifstream fpy( "test.txt", std::ios::binary );
  fpy.read( (char *)signPy.c_str(), signPy.size() );
}

That creates a string of 256 bytes initialized to zeros.
Then it creates an input file stream and reads up to 256 bytes (fewer if the file is too small).
Notice also that the file object is a temporary, created and automatically destroyed in its own local context.

To print it the way your example lists it (as a string of C-escape sequences):

{
  std::ostringstream oss;
  oss << std::hex;
  for (unsigned c : signPy)
    oss << "\\x" << std::setfill('0') << std::setw( 2 ) << (c & 0xFF);
  std::cout << oss.str() << "\n";
}

There are a multitude of other ways, but a simple loop here using a temporary stream is about as simple as you can get, even if it is ugly. You can make life prettier and shorter at the output point, but that requires additional code elsewhere.

CodePudding user response:

In your code, you are using the C ways to handle files.

In C , we use something called fstream for handling files:

#include <iostream>
#include <string>
#include <fstream>

int main()
{
    // ifstream - in file stream - used for reading from a file
    std::ifstream in("inputt.txt"); 

    // ofstream - out file stream - used for writing to a file
    std::ofstream out("outputt.txt"); 

    int sum = 0;

    std::string line;
    while (std::getline(in, line))
    {
        sum  = std::stoi(line);
    }

    std::cout << sum;
    out << sum;
}

The above code will take all the numbers from the file input.txt and store the sum of all the numbers in output.txt.

  •  Tags:  
  • c
  • Related