gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:38:38 25 4
gpt4 key购买 nike

我正在尝试读取这两个文件的大小以确定两个文件中哪个较小,但第二个文件的结果总是为零,而第一个文件的大小甚至都不正确,有什么想法吗?

#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 的返回值。

关于c - fstat() 没有读取正确的文件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24897309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com