Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8778243
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T19:29:02+00:00 2026-06-13T19:29:02+00:00

I am trying to read binary files and storing the content into a char

  • 0

I am trying to read binary files and storing the content into a char array. This function is working great for text files, but for non-text files (a PNG file for example) it does not work as expected. Below is the code followed by the results. What is wrong?

Code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>

unsigned int readFile(const char *fileName, char **contents);

int main(int argc, char *argv[])
{
    char *contents = 0;
    unsigned int length = readFile(argv[1], &contents);

    fprintf(stderr, "File length: %d\r\n", length);
    fprintf(stderr, "File contents:\r\n%s\r\n", contents);

    exit(0);
}

unsigned int readFile(const char *fileName, char **contents)
{
    struct stat stbuf;
    unsigned int length = 0;

    // Open a file descriptor
    int fd = open(fileName, O_RDONLY);

    // Check that file descriptor was opened
    if (fd == -1) {
        fprintf(stderr, "Fatal Error: Failed to open the file for fstat (file: %s)!\r\n", fileName);
        exit(-1);
    }

    // Get information from fstat
    if (fstat(fd, &stbuf) == -1) {
        fprintf(stderr, "Fatal Error: Failed to find file length (file: %s)!\r\n", fileName);
        exit(-1);
    }

    // Store the file length
    length = stbuf.st_size;

    // Close file descriptor
    if (close(fd) == -1) {
        fprintf(stderr, "Fatal Error: Failed to close file descriptor (file: %s)!\r\n", fileName);
        exit(-1);
    }

    // Check if the file contains data
    if (length > 0) {
        // Open the file for reading
        FILE *file = fopen(fileName, "rb");

        // Check that the file was opened
        if (file != NULL) {
            freopen(fileName, "rb", file);
            // Prepare the contents variable
            *contents = 0;
            *contents = (char*)calloc(length + 1, sizeof(char));

            // Read the file and put it in the contents variable
            int lengthRead = fread(*contents, length, 1, file);

            // Check for file read error
            if (ferror(file)) {
                fprintf(stderr, "Fatal Error: Failed to read file (file: %s)!\r\n", fileName);
                exit(-1);
            }
            else if (lengthRead != 1 || strlen(*contents) < length) {
                fprintf(stderr, "Fatal Error: File read error (file: %s)!\r\n", fileName);
                fprintf(stderr, "Characters expected: %d, Characters read: %d\r\n", length, strlen(*contents));
                fprintf(stderr, "Content read:\r\n%s\r\n", *contents);
                fprintf(stderr, "Aborting!\r\n", fileName);

                // Close file and exit
                fclose(file);
                exit(-1);
            }

            // Close binary file
            fclose(file);
        }
        else {
            fprintf(stderr, "Fatal Error: Failed to open the file: %s!\r\n", fileName);
            exit(-1);
        }
    }
    else {
        fprintf(stderr, "Fatal Error: File was empty (file: %s)!\r\n", fileName);
        exit(-1);
    }

    return length;
}

Results:

devious@devious-kubuntu:~/Workspace/test$ ls                                                                                                                                                                                                                                   
test  test.c  test.png  test.txt
devious@devious-kubuntu:~/Workspace/test$ ./test test.txt 
File length: 43
File contents:
This is a test file!

With multiple lines!

devious@devious-kubuntu:~/Workspace/test$ ./test test.png 
Fatal Error: File read error (file: test.png)!
Characters expected: 50243, Characters read: 8
Content read:
?PNG
¦

Aborting!

I would expect these results if I opened the file in text mode, but since it is opening in binary mode, I do not see why this is happening.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T19:29:03+00:00Added an answer on June 13, 2026 at 7:29 pm

    The strlen function is exclusively for use on C-style strings. There is no way to tell the length of arbitrary binary data by looking at its content. You have the length in lengthRead.

                fprintf(stderr, "Content read:\r\n%s\r\n", *contents);
    

    Same problem here. The %s format specifier is for C-style strings, not arbitrary binary data. You’ll need to write your own function to print the data in some appropriate format.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to read a binary file that consists of 2 byte floats, but
I'm experiencing some problems while trying to read a binary file in C. This
I'm trying to read data from a binary file and put it into a
i'm trying to read a binary file (for example an executable) into a string,
Hi i am trying to save text values as binary file and read from
I am storing information about files that I read in from files in binary.
I'm trying to read a remote binary file (say, image) from internet like this:
I'm trying to read binary data to load structs back into memory so I
I am trying to read a .gz file and print the text content on
I am trying to read a binary file and store it into a database,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.