Hello, I'm writing the simple code as below

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

int main()
{

FILE *fp;
float x,y;
int n;

int errno = 0;
int i;


fp=fopen("test_numbers.dat","w");

for(i=1;i<=10;i++)
    fprintf(fp,"%d  %d\n",i,i*i);

fclose(fp);

fp=fopen("./test_numbers.dat","r");

if(fp==NULL);
    printf("File cannot be opened\n");

fclose(fp);


return 0;


}

and save it as main.c
I'm compiling the program using the command gcc -o exec main.c.
After execution I'm receiving "File cannot be opened"
So the fp pointer is NULL! Why this? I've double checked the file and the permissions but I assume nothing goes wrong. Please help me! Thanks in advance

You are opening the file twice, once for writing & once for reading. The 2 commands you use are:

fp=fopen("test_numbers.dat","w");
fp=fopen("./test_numbers.dat","r");

Perhaps you are trying to read the file in a different folder? Have you tried:

fp=fopen("test_numbers.dat","r");

I found the error, was the semicolon at the end of if statement

if(fp==NULL);

Sharp eye! Too bad that the compiler does not catch an obvious mistake like this. :)

if(fp==NULL)
    ;  // do nothing

is correct code

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.