fstat()没有读取正确的文件大小

时间:2014-07-22 20:35:07

标签: c file io byte

我正在尝试读取2个文件的大小以确定哪两个较小,但第二个文件总是出现零,第一个大小甚至不正确,有什么想法吗?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{

    struct stat buf1;
    struct stat buf2;

    FILE *fp1, *fp2;
    int ch1, ch2;
    clock_t elapsed;
    char fname1[40], fname2[40];

    printf("Enter name of first file:");
    fgets(fname1, 40, stdin);
    while ( fname1[strlen(fname1) - 1] == '\n')
    {
        fname1[strlen(fname1) -1] = '\0';
    }

    printf("Enter name of second file:");
    fgets(fname2, 40, stdin);
    while ( fname2[strlen(fname2) - 1] == '\n')
    {
        fname2[strlen(fname2) -1] = '\0';
    }

    fp1 = fopen(fname1, "r");
    if ( fp1 == NULL )
    {
        printf("Cannot open %s for reading\n", fname1 );
        exit(1);
    }

    fp2 = fopen(fname2,  "r");
    if (fp2 == NULL)
    {
        printf("Cannot open %s for reading\n", fname2);
        exit(1);
    }

    //int name1 = fopen(fname1, "r");
    //int name2 = fopen(fname2, "r");

    stat(fp1, &buf1);
    int size1 = buf1.st_size;

    stat(fp2, &buf2);
    int size2 = buf2.st_size;

    printf("Size of file 1: %d\n", size1);
    printf("Size of file 2: %d\n", size2);

    elapsed = clock(); // get starting time

    ch1  =  getc(fp1); // read a value from each file
    ch2  =  getc(fp2);

    unsigned long long counter = 0;
    unsigned long long total = 0;

    while(1) // transform this into a for loop
    {
        ch1 = getc(fp1);
        ch2 = getc(fp2);

        if((ch1 ^ ch2) == 0) // try to change this into a for loop?
        {
            counter++;
        }

        total++;

        if ( ( ch1 == EOF) || ( ch2 == EOF)) // if either file reaches the end, then its over!
        {
            break; // if either value is EOF
        }
    }


    fclose (fp1); // close files
    fclose (fp2);

    float percent = (float)counter / (float)total * 100.0f ;

    printf("Counter: %u Total: %u\n", counter, total);
    printf("Percentage: %.2f%\n", percent);

    elapsed = clock() - elapsed; // elapsed time
    printf("That took %.4f seconds.\n", (float)elapsed/CLOCKS_PER_SEC);
    return 0;
}

结果如下:

Enter name of first file:air.197901.nc
Enter name of second file:air.197902.nc
Size of file 1: 1340845192
Size of file 2: 0
Counter: 147701939 Total: 1256756880
Percentage: 11.75
That took 105.8533 seconds.

1 个答案:

答案 0 :(得分:2)

您的代码甚至没有调用fstat。您正在调用stat,但是将FILE指针传递给它而不是路径名。你需要做:

stat(fname1, &buf1);

或:

fstat(fileno(fp1), &buf1);

此错误应该会从编译器产生错误(或至少是警告)。

此外,您应该检查statfstat的返回值。