是否可以停止扫描文件中间的文件?

时间:2017-05-18 18:27:38

标签: c file

是否可以停止扫描文件中间的文件? 例如,如果我想将此代码更改为for size / 2。

编辑:你能帮我理解为什么我!= 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++;
    }

1 个答案:

答案 0 :(得分:2)

是的,您可以get the file size然后循环播放:

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

一个例子:

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