无法使用fread函数读取完整数据

问题描述 投票:0回答:1

我有一个图像文件,我试图从文件的第 54 个字节读取 8 个字节的数据并将其存储在字符数组(大小为 8 个字节)中。但在执行时,即使指针已从其起始位置向前移动了 8 个字节(从第 54 个字节到第 62 个字节),它也仅读取 8 个字节。当我尝试打印已成功保留的 1 字节数据时,它没有打印任何内容。

#include<stdio.h>
int main()
{
    FILE *fptr_stego;
    FILE *fptr_text;
    size_t f_size = 0;
    char str[8];

    // opening image file
    fptr_stego = fopen("stego.bmp", "r");
    if(fptr_stego == NULL)
    {   
        printf("FAILED to open stego file\n");
        return 0;
    }   

    // opening text file
    fptr_text = fopen("decode.txt", "w");
    if(fptr_text == NULL)
    {   
        printf("FAILED to open text file\n");
        return 0;
    }   

    printf("Successfully opened both files\n");

    // shifting pointer to 54th byte
    fseek(fptr_stego, 54, SEEK_SET);
    printf("File pointer location before reading %ld\n", ftell(fptr_stego));
    
    //read from stego image file
    f_size = fread(str, 8, sizeof(char), fptr_stego);
    if(f_size != 8)
    {   
        printf("Unable to fetch 8 bytes\n%ld bytes read at %ld position\n", f_size, ftell(fptr_stego));
        printf("Data retained: %c\n", str[0]);
        return 0;
    }


    // close files
    fclose(fptr_stego);
    fclose(fptr_text);

    printf("Data read successfull\n");
    return 0;
}
Successfully opened both files 
File pointer location before reading 54
Unable to fetch 8 bytes1 bytes read at 62 position
Data retained:

这是我执行时得到的输出。我已经使用

hd stage.bmp
命令检查了图像文件数据,它包含所有数据。我之前已经在图像文件中完成了编码,当时它工作得很好,但现在当我尝试从文件中解码数据时,这是我在通过 fread 函数读取图像文件时遇到的问题。

c fread
1个回答
1
投票

您混淆了

fread()
的两个参数,一个元素的大小和元素的数量。

fread()
的概要是:

size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);

并且

fread()
返回它读取的元素数量。

你这样称呼它:

fread(str, 8, sizeof(char), fptr_stego);

显然,

8
是元素的请求大小,
sizeof (char)
是元素的数量。由于后者始终为 1,因此返回值也为 1。

交换两个值,一切顺利:

fread(str, sizeof(char), 8, fptr_stego);

© www.soinside.com 2019 - 2024. All rights reserved.