Andrew Dushkin
Andrew Dushkin

Reputation: 37

Maximum number "C"

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:

  1. I'm not very good in programing and in english(so if u will try to explane me something in english i don't think that i'll understand every word)
  2. In the end there should be the max number on da screen, but it shows me the very first number
  3. 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

Answers (2)

user3121023
user3121023

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

Marc B
Marc B

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

Related Questions