Exiting out of file with feof function

前端 未结 1 1421
天涯浪人
天涯浪人 2021-01-28 06:18

I am trying to make a photo extraction program stop when it detects it is at the end of the file to be extracted. I did this by placing an if condition:

if (feof(         


        
1条回答
  •  借酒劲吻你
    2021-01-28 06:27

    Don't open and close the file each time through the loop. Just read the file in blocks of 512 until this reaches EOF.

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

    0 讨论(0)
提交回复
热议问题