繁体   English   中英

fstat()无法读取正确的文件大小

[英]fstat() not reading the correct file size

我正在尝试读取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.

您的代码甚至没有调用fstat 您正在调用stat但将FILE指针而不是路径名传递给它。 您需要执行以下任一操作:

stat(fname1, &buf1);

要么:

fstat(fileno(fp1), &buf1);

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM