0

I have a question in #c.

the code print all time "error" .

I try to do debugging but i didnt succeeded. The code should not enter the condition and it does enter the condition. What is the problem?

the code is:

int main()
{
    char name[10];
    int number_cores = 0, size = 0, grade = 0;
    float avarge = 0.0, sum = 0.0;
    FILE* fp = NULL;
    FILE *fwrite = NULL;
    int i;
    fp = fopen("grades.txt", "r");
    if (fp)
    {
        printf("error");
        return 0;
    }
    fwrite = fopen("averages.txt", "w");
    if (fwrite)
    {
        printf("error");
        return 0;
    }
    while (!feof(fp))
    {
        fscanf(fp, "%s", name);
        fprintf(fwrite,"%s:", name);
        fscanf(fp,"%d", &number_cores);
        sum = 0, grade = 0;
        for (i = 0; i < number_cores; i++)
        {
            fscanf(fp, "%d", &grade);
            sum += grade;
        }
        avarge = (sum / number_cores);
        fprintf(fwrite, "%f\n",avarge);
    }
    fclose(fwrite);
    fclose(fp);


    return 0;

}



Efrat
  • 1
  • 1
    Not sure it's your problem, but see [Why is `while( !feof(file) )` always wrong?](https://stackoverflow.com/questions/5431941) – Steve Summit Nov 06 '22 at 17:50
  • 2
    Best to not name a variable `fwrite` since that is a name used by the standard library. `if (fwrite)` checks if the file pointer is not NULL which it wouldn't be if the file was successfully opened. Perhaps you want `if (!fwrite)` so the error only happens when the file isn't opened? Same issue with `fp` earlier. – Retired Ninja Nov 06 '22 at 17:50
  • 2
    What is "#C"? Your code looks like C, so you probably didn't mean C#. (But if it was supposed to be a hashtag, this here is Stack Overflow, not Twitter. :-) ) – Steve Summit Nov 06 '22 at 17:51
  • `perror` is your friend. Use it. – n. m. could be an AI Nov 06 '22 at 17:54

1 Answers1

3

You are checking for errors from fopen incorrectly. These functions return NULL on failure or valid pointers on success. if(fp) checks if fp is such a valid pointer, but you're using it as an error indication which causes 'error' to be printed to standard output.

What platform are you writing for? POSIX and Windows both set errno when the standard I/O functions fail, so it's better to use perror() to print detailed error information to standard error.

As pointed out in the comments, you should not call a variable fwrite, since that clashes with the name of the standard I/O function (and you are using standard I/O functions here).

JohnScott
  • 82
  • 4