C fread 未获取整个文件

标签 c fread

我正在尝试读取二进制文件并将内容存储到字符数组中。此功能对于文本文件非常有效,但对于非文本文件(例如 PNG 文件),它无法按预期工作。下面是代码和结果。怎么了?

代码:

#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;
}

结果:

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!

如果我以文本模式打开文件,我会期望得到这些结果,但由于它是以二进制模式打开的,所以我不明白为什么会发生这种情况。

最佳答案

strlen 函数专门用于 C 样式字符串。无法通过查看任意二进制数据的内容来判断其长度。 lengthRead 中有长度。

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

这里有同样的问题。 %s 格式说明符适用于 C 样式字符串,而不是任意二进制数据。您需要编写自己的函数来以某种适当的格式打印数据。

关于C fread 未获取整个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13223666/

相关文章:

clang:不能将 'precompiled-header' 输出与多个 -arch 选项一起使用

c - fread 不读取整个文件

c - 读取并收集文本文件中的变量

c - 从二进制文件中读取并复制到数组中

c - 使用 pthreads 逐行读取文件...意外退出

c - 如何使用 memcpy 设置字节数?

c++ - 具有非唯一键的直接地址表

c++ - 如何在 C/C++ 中生成表的所有组合的数组列表

c - 在 C 中逐行浏览文本文件

PHP 控制台脚本/传递默认参数/重构 fopen() fread() fwrite() fclose()