Home > OS >  When Opening Files in C why do I have to use a different Macro to define the file then I use to decl
When Opening Files in C why do I have to use a different Macro to define the file then I use to decl

Time:11-16

I have been playing with text files in C and have found out macros get weird when interacting with text files.

So can someone explain to me why this compiles...

#include <stdio.h>
#include <stdlib.h>
#define FILENAME "Distribution.txt"

int main()
{
    float zvalue[13][10];

    FILE *fp;
    fp = fopen("Distribution.txt", "r");

    for (int a=0; a<13; a  ) {
    for (int b=0; b<10; b  ) {
    fscanf(fp, "%d", &zvalue[a][b]);
    }
    }

    printf("%f", zvalue[0][0]);

    fclose(fp);

    return 0;
    //This compiles
}

But when line three is changed to FILE instead of FILENAME it does not?

#include <stdio.h>
#include <stdlib.h>
#define FILE "Distribution.txt"

int main()
{
    float zvalue[13][10];

    FILE *fp;
    fp = fopen("Distribution.txt", "r");

    for (int a=0; a<13; a  ) {
    for (int b=0; b<10; b  ) {
    fscanf(fp, "%d", &zvalue[a][b]);
    }
    }

    printf("%f", zvalue[0][0]);

    fclose(fp);

    return 0;
    //This does not compile

}
```


CodePudding user response:

FILE is defined by the C standard. It is the type that the fopen returns a pointer to. If you look a few lines down in your code, you can see that you are using FILE for that purpose. Therefore, redefining it can cause all sorts of problems and you should not do it.

CodePudding user response:

Macros are automatic copy/paste.

When you write

#define FILE "Distribution.txt"

it tells the compiler that from now on, whenever you wrote FILE, it should pretend you wrote "Distribution.txt" instead.

So then when it sees this line:

FILE *fp;

it pretends you wrote this line:

"Distribution.txt" *fp;

which is not valid.

CodePudding user response:

FILE is a predefined struct name in c.

You cant use it as MACRO

  • Related