I am trying to read the size of the 2 files to determine which of the two are smaller, but the second file always comes out to zero and the first size is not even correct, any ideas?
#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;
}
Here are the results:
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.
Your code is not even calling fstat
. You're calling stat
but passing a FILE
pointer to it rather than a pathname. You need to either do:
stat(fname1, &buf1);
or:
fstat(fileno(fp1), &buf1);
This mistake should have produced an error (or at least a warning) from the compiler.
Also, you should be checking the return value of stat
or fstat
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.