读取错误的有效字节数C

问题描述

我读取了两张ppm图像,并且有一个结构可以存储所有信息(幻数,宽度,高度,颜色级别和像素)。我使用fread读取像素,但问题是我们需要运行一些测试以查看我们的代码是否有效并可以创建新的ppm。一个测试必须无效(因为像素数与给定的大小不同,所以不创建图像),但是我的代码还是创建了图像,因为在fread中读取的成功字节必须为83(退出该条件的条件代码是,如果字节数与给定的大小(宽度*高度* 3)不同,我们返回1并停止执行),但实际上它读取的是等于大小的84个字节,则它将继续执行代码,而不是阻止它,而我不明白为什么。错误发生在读取的像素注释之后。 附言:因为该代码可以给出两个图像,所以我两次给出相同的无效图像。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct image
{
    char *magicNumber;
    int width;
    int height;
    int level;
    uint8_t *pixels;
};

int main(int argc,char *argv[])
{
    struct image img1;
    struct image img2;
    struct image img3;

    // Read files
    FILE *file1 = fopen(argv[1],"r");
    FILE *file2 = fopen(argv[2],"r");

    // Check files
    if (!file1 || !file2)
    {
        fprintf(stderr,"Error while opening the file.\n");
        return 1;
    }

    // Alloc memory for pixels array
    img1.magicNumber = (char *)malloc(3 * sizeof(char));
    img2.magicNumber = (char *)malloc(3 * sizeof(char));

    // Take magic number
    fscanf(file1,"%s",img1.magicNumber);
    fscanf(file2,img2.magicNumber);

    // Check magic number
    if (strcmp(img1.magicNumber,"P6") != 0 || strcmp(img2.magicNumber,"P6") != 0)
    {
        fprintf(stderr,"Invalid magic number.\n");
        return 1;
    }
    // Take width
    fscanf(file1,"%d",&img1.width);
    fscanf(file2,&img2.width);
    // Take height
    fscanf(file1,&img1.height);
    fscanf(file2,&img2.height);

    // Check size
    if (img1.width != img2.width || img1.height != img2.height)
    {
        fprintf(stderr,"Invalid Dimension.");
        return 1;
    }
    // Take level
    fscanf(file1,&img1.level);
    fscanf(file2,&img2.level);

    // Check level
    if (img1.level != 255 || img2.level != 255)
    {
        fprintf(stderr,"Invalid Level.");
        return 1;
    }
    // Alloc memory for pixels array
    img1.pixels = (uint8_t *)malloc(img1.width * img1.height * 3 * sizeof(uint8_t));
    img2.pixels = (uint8_t *)malloc(img2.width * img2.height * 3 * sizeof(uint8_t));

    // Read pixels
    size_t nrPixel1 = fread(img1.pixels,sizeof(uint8_t),img1.width * img1.height * 3,file1);
    size_t nrPixel2 = fread(img2.pixels,img2.width * img2.height * 3,file2);

    // Check pixels read
    if (nrPixel1 != img1.width * img1.height * 3 || nrPixel2 != img2.width * img2.height * 3)
    {
        fprintf(stderr,"Invalid pixels.");
        return 1;
    }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)