Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
507 views
in Technique[技术] by (71.8m points)

c - Image data is not fetched in entirety when reading an image of unknown size

I have an image file that I'm trying to read and store in a buffer buffer.

However, I'm only picking up the first few characters, and not the entire file. I also don't know the total length of the file, so I unfortunately can't tell it to read X number of characters.

Here is my code:

#include <stdio.h>
int main() {
    char *data;
    read_file("Dragon.png", &data);
    printf("%s", data);
}

int read_file(char *file, char **buffer) {

    FILE *file_r = fopen(file, "rb");
    
    if (file_r != NULL) {
    
        fseek(file_r, 0, SEEK_END); // Set file position to end of file
        unsigned long file_size = ftell(file_r); // Record the position (find the total size of the file)
        fseek(file_r, 0, SEEK_SET);  // Move back to the beginning to begin reading
        
        *buffer = malloc(file_size + 1); // Allocate buffer memory
        fread(*buffer, 1, file_size, file_r);
        fclose(file_r);
        
        return file_size; // File read and passed
    }
    return -1; // File not found (or other error)
}

When running:

$ gcc read-file.c -oa
$ ./a
?PNG
?
$ 

I have no idea how to fix this. How should I proceed?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...