Reputation: 37
i'm a begginer in programming and i have a task. I need to find the maximum number from file in.txt
with content: 2,5,4,6,7,10 and then write it to file out.txt
. Language C
. The problems are:
It's not my first theme here and every time the moderator give a link were i can read some text and find the answer, but look at priblem(1) there are too much text and i cannot tranlate everything in those answers(themes) So help me please i'm a noob/ I have some code:
#include <conio.h>
#include <stdio.h>
main()
{
int N, max;
FILE *F;
F = fopen("in.txt", "r"); // open file
FILE *G;
G = fopen("out.txt", "w"); // open file
fscanf(F, "%d", &max);
while (feof(F))
{
fscanf(F, "%d", &N);
if (max < N)
max = N;
}
printf("max=%d", max); // show the result on the screen
fprintf(G, "%d", max); // put result into out.txt
fclose(F);
fclose(G);
}
Upvotes: 0
Views: 109
Reputation: 8286
Check to see if fopens succeed. Check if scanf succeed.
scanf will fail at EOF and drop out of loops
#include <stdio.h>
int main ()
{
int N,max;
FILE*F;
F=fopen("in.txt","r"); //open file
if ( F == NULL) { // check if fopen failed
printf ( "could not open in.txt\n");
return 1;
}
FILE*G;
G=fopen("out.txt","w"); //open file
if ( G == NULL) {
fclose ( F);
printf ( "could not open out.txt\n");
return 1;
}
if ( ( fscanf(F,"%d",&max)) == 1) // read an int into max. if success return is 1
{
while( ( fscanf(F,"%d",&N)) == 1) // read an int into N. if success return is 1
{
if(max<N)
{
max=N;
}
}
printf("max=%d",max);//show the result on the screen
fprintf(G,"%d",max); //put result into out.txt
}
fclose(F);
fclose(G);
return 0;
}
Upvotes: 0
Reputation: 360612
Typo:
while(!feof(F))
^--- missing
feof
returns TRUE
if you're at the end of the specified file handle. Since you just started reading that file, you're NOT at the end, so feof()
will return FALSE
, and terminate your loop. You never actually read any further numbers.
Adding the !
makes it into "while NOT at the end of the file, read numbers".
Upvotes: 3