Saga
Saga

Reputation: 77

Is it possible to stop scanning from file in the middle of the file?

Is it possible to stop scanning from file in the middle of the file? For example if I want to change this code to for loop with size/2.

edit: Can you please help me understand why i != toScan size(secondSize)?

fseek(toScan, 0, SEEK_END);
secondSize = ftell(toScan);
rewind(toScan);

fseek(toScan, 0.5 * secondSize, SEEK_SET);

while (fgetc(toScan) != EOF){
        rewind(signature);
        fseek(toScan, -1, SEEK_CUR);
        if (fgetc(toScan) == fgetc(signature)){
            fseek(toScan, -1, SEEK_CUR);
            temp = ftell(toScan);
            elements = fread(secondBuffer, 1, size, toScan);
            fseek(toScan, temp + 1, SEEK_SET);

            if (strcmp(secondBuffer, buffer) == 0){
                toReturn = 3; 
                break;
            }
        }

        rewind(signature);
        strncpy(secondBuffer, "", sizeof(secondBuffer));
        i++;
    }

Upvotes: 1

Views: 103

Answers (1)

David Ranieri
David Ranieri

Reputation: 41046

Yes, you can get the file size and then, in a loop:

for (i = 0; i < file_size / 2; i++) {
    int c = fgetc(file);
    ...
}

An example:

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

int main(void)
{
    FILE *file;
    long size, i;
    int c;

    file = fopen("demo.c", "rb");
    if (file == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    if (fseek(file, 0, SEEK_END) == -1) {
        perror("fseek");
        exit(EXIT_FAILURE);
    }
    size = ftell(file);
    if (size == -1) {
        perror("ftell");
        exit(EXIT_FAILURE);
    }
    if (fseek(file, 0, SEEK_SET) == -1) {
        perror("fseek");
        exit(EXIT_FAILURE);
    }
    for (i = 0; i < size / 2; i++) {
        c = fgetc(file);
        putchar(c);
    }
    fclose(file);
    return 0;
}

Upvotes: 2

Related Questions