skip to Main Content

I don’t understand why is marking as identifier "FILE" is undefined. Firstly I thought it was because of the includes, but in my code I include <stdio.h>. Then I thought that it was just a "marking" squiggle, but when I execute in the terminal shows segmentation fault, so I don’t know what I can do.
Here is my program:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main() {
    FILE *fp;
    fp = fopen("taula.txt", "W");
    for (double i = -0.001; i < 0.001; i += 0.00001) {
        fprintf(fp, "%lf %.14lf n", i, -pow(i,4)*1/(840)+(i*i)*1/(30)-1/3);
    }
    fclose(fp);
    return 0;
}

I’m using Visual Studio Code 1.71.2 (Universal), clang as compiler and the OS I use is macOS Monterey 12.6 in MacBook Pro with M1 Pro.
I hope someone can solve my problem.

2

Answers


  1. I cannot say why it claims that FILE is undefined — on that front, your code looks fine to me, and it compiles without issues (and since you can run it, I assume it must have compiled for you too, which it wouldn’t have if FILE was indeed undefined).

    It does, however, segfault. I strongly recommend that you check that the return value of fopen isn’t NULL, and, when you have found out that it is, that you read the fopen manpage carefully, especially the section on what the legal values for the second argument are.

    EDIT: And the comment about constants being ints is worth listening to, even if that’s unlikely to cause segfaults.

    Login or Signup to reply.
  2. The error reported for FILE seems unwarranted. Check these possibilities:

    • maybe the compiler cannot find the standard header files, but it should report this as an error too.
    • is there is an empty file called stdio.h somewhere in your include path?

    Note also these problems:

    • to open the file for writing, you should use "w", not "W".
    • you should test for fopen failure, which probably happens because of the above mistake.
    • the number of iterations in the loop may not be exactly 200 because of cumulative errors adding 0.00001, which cannot be represented exactly using binary floating point representation.
    • the expression -pow(i,4)*1/(840)+(i*i)*1/(30)-1/3 seems incorrect: 1/3 evaluates to 0 because it uses integer arithmetics.

    Here is a modified version:

    #include <errno.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main() {
        FILE *fp = fopen("taula.txt", "w");
        if (fp == NULL) {
            fprintf(stderr, "cannot open taula.txt: %sn", strerror(errno));
            return 1;
        }
        for (double j = -100; j < 100; j += 1) {
            double i = j / 100000.;
            double i2 = i * i;
            fprintf(fp, "%f %.14fn", i, -i2*i2/840. + i2/30. - 1./3.);
        }
        fclose(fp);
        return 0;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search