Originally Posted by
Raven_
Hello there guys,
I need some help with my program. My program is supposed to collect and return the greater values from two binary files, which contain numbers, and amount of numbers are equal. Then write the values into the third binary file.
I have two files which contain: 12 34 and 11 35, so it is supposed to collect 12 35. So the problems is that the program only collects the only one number from the end, like only 35 and I have no clue how to fix this.
It's not worth fixing. You really need to start over. I'll comment the code so you can see why...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
FILE *fp, *firstfile, *secondfile;
//char file_name[260];
int firstfilenum=0, secondfilenum=0, thirdfilenum=0;
/* File creation
int f;
printf("\nFile name: "); // Why are you creating a file???
scanf("%s", file_name);
fp = fopen(file_name, "wb");
printf("Enter information. To end press ctrl+z\n");
while(!feof(stdin)){ // Loop until eof, and
scanf("%d", &f);
if (!feof(stdin)) // test for eof? Why 2 tests?
// Make you loop more intelligent
fwrite(&f, sizeof(int), 1, fp);
}
fclose(fp);
*/
firstfile = fopen("1.dat" , "r"); // using fread? Is this a text or
// a binary file?
printf("Numbers on the first file: ");
while (!feof(firstfile)) // You should already see why
// you don't want to use FEOF here....
{
fread(&firstfilenum,sizeof(int),1,firstfile); // you read each binary value
// and throw it away
printf("%d ", firstfilenum);
}
secondfile = fopen("2.dat" , "r"); // now you do it again with
// the second file....
printf("\nNumbers on the second file: ");
while(!feof(secondfile))
{
fread(&secondfilenum,sizeof(int),1,secondfile);
printf("%d ", secondfilenum);
}
fp = fopen("3.dat", "wb");
while(!feof(fp))
{
fscanf(firstfile,"%d",&firstfilenum); // Now you read a text value,
// but you've already reached EOF!
fscanf(secondfile,"%d",&secondfilenum); // what value is in your
// variable after these reads?
thirdfilenum = fmax(firstfilenum, secondfilenum);
// FMAX is not a standard C
// function -- does it exist?
{
fwrite(&thirdfilenum, sizeof(int), 1, fp); }
{
printf("\nSelected numbers to the third file: ");
{
rewind(fp);
fread(&thirdfilenum,sizeof(int),1,fp);
printf("%d\n\n", thirdfilenum);
}
fclose(firstfile);
fclose(secondfile);
fclose(fp);
system("pause");
return 0;
}
}
}