首页 > 解决方案 > 以涉及 fread 的条件退出程序

问题描述

我正在为我正在学习的课程开发照片提取程序。

对于这个程序,argv[1] 是我要从中提取图像的文件的名称。jpg_name 与我正在提取的每张图像的名称相关;我正在尝试命名每个 jpg。数字从 1 开始。由于要提取 50 张照片,我想在提取完所有 50 张图像后停止程序。不幸的是,我的程序不确定何时终止,因此我相信最后一张照片被多次覆盖,我不确定如何解决这个问题。但是,照片 1-49 效果很好,只是照片 50 我遇到了问题。

我尝试过的事情包括实现一个if条件fread,如果程序无法将 512 字节的代码读入数组,它将终止。不幸的是,这似乎也不起作用。任何建议,将不胜感激:

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

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Invalid entry.\n");
        return 0;
    }

    int counter = 1;
    FILE* images;
    char jpg_name[8];

    // Check if bytes are jpg. signatures.
    for (int n = 0; counter < 51; n = n + 512)
    {
        // Open file for reading.
        FILE *file = fopen(argv[1], "r");
        if (!file)
        {
            return 1;
        }

        unsigned char array[512];
        fseek(file, n, SEEK_SET);
        fread(array, 1, 512, file); // if EOF, won't have 512 to write into!!!
        if (fread(array, 1, 512, file) != 512)
        {
            return 2;
        }

        if (array[0] == 0xff && array[1] == 0xd8 && array[2] == 0xff && (array[3] & 0xf0) == 0xe0)
        {
            // Convert integer to string and store into jpg character array. Increment image number.
            sprintf(jpg_name, "%03i.jpg", counter);
            counter++;

            // Open images file to write into, allocate memory to jpg file to write into, write 512 bytes from array into image file.
            images = fopen(jpg_name, "a");
            fwrite(array, 1, 512, images);
            fclose(images);
        }
        else // If 1st 4 bytes aren't jpg signature.
        {
            if (counter > 1)
            {
                images = fopen(jpg_name, "a");
                fwrite(array, 1, 512, images);
                fclose(images);
            }
        }
        fclose(file);
    }
}

标签: ccs50eoffread

解决方案


您似乎对函数和返回调用有一个基本的误解。我怀疑你认为:一条fread指令读取数据,一条if指令检查某事是否属实。所以你读取数据,然后检查读取了多少。但是,您错过了if执行内部指令()以查看结果是否为真的事实。所以if(fread(array, 1, 512, file) != 512)读取数据检查结果。

如果要读取数据并检查结果,请使用if(fread(array, 1, 512, file) != 512). 如果要读取数据而不检查结果,请使用fread(array, 1, 512, file);. 不要同时使用两者。

您还可以选择使用变量,例如:

int number_of_bytes_read = fread(array, 1, 512, file);
if(number_of_bytes_read != 512) // this doesn't read data, it just gets the number from the variable
{
    ...

推荐阅读