Выход из файла с помощью функции feof - PullRequest
0 голосов
/ 14 июля 2020

Я пытаюсь остановить программу извлечения фотографий, когда она обнаруживает, что находится в конце извлекаемого файла. Я сделал это, поместив условие if:

if (feof(file))
{
   return 2;
}

После функции fread:

fread(array, 1, 512, file);

Так что, если fread читает до конца файла, то запускается feof и, следовательно, завершить программу. Это мой код:

#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 (feof(file))
        {
            return 2;
        }
        fclose(file);

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

Я также попытался поместить условие:

if (fread(array, 1, 512, file) == 512)

в программу, чтобы она перестала работать после того, как прочитает менее 512 байт, чтобы остановить автоматическую остановку программа, но она, похоже, тоже не работает.

Любые разъяснения или советы были бы очень признательны, спасибо!

1 Ответ

0 голосов
/ 14 июля 2020

Не открывать и не закрывать файл каждый раз через l oop. Просто прочтите файл блоками по 512, пока он не достигнет EOF.

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

#define SIZE 512

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

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

    // Open file for reading.
    FILE *file = fopen(argv[1], "r");
    if (!file)
    {
        return 1;
    }

    unsigned char array[SIZE];

    // Check if bytes are jpg. signatures.
    while (fread(array, 1, SIZE, file) == 1)
    {
        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);
}
...