0

I find this code in a website:

    struct person 
{
    int id;
    char fname[20];
    char lname[20];
};
  
int main ()
{
    FILE *outfile;
      
    // open file for writing
    outfile = fopen ("person.dat", "w");
  
    struct person input1 = {1, "rohan", "sharma"};
      
    // write struct to file
    fwrite (&input1, sizeof(struct person), 1, outfile);

     if(fwrite != 0) 
        printf("contents to file written successfully !\n");

    return 0;
}

  1. Is line if(fwrite != 0) correct?
  2. Does we can compare function name itself(fwrite)?
  3. What is value of fwrite in this case?

1 Answers1

2

No, that's definitely not the correct way to do it. The correct way is this:

if(fwrite(&input1, sizeof(struct person), 1, outfile)) != 1) {
    /* Error writing */
}

But in order to avoid duplicate magic numbers, this would be better:

size_t num = 1;
if(fwrite(&input1, sizeof(struct person), num, outfile)) != num) {

I find it hard to believe ANY site would publish rubbish code like that. I knew geeksforgeeks isn't very trustworthy, but this was incredibly bad. It's wrong on so many levels.

if(fwrite != 0) is a completely pointless check. If fwrite != 0 would evaluate to false, it would mean that the function call to fwrite would fail. The check basically means "Is fwrite a null pointer?" And if a library function is a null pointer, then something is REALLY wrong.

fwrite returns the number of elements written, which in this case should be one element.

I wrote a rant about Tutorialspoint earlier, but now I need to add geeksforgeeks to my list of resources I recommend to stay far, far away from.

klutt
  • 30,332
  • 17
  • 55
  • 95