0

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

Edited by Dimitris_1: Unessecary code

3
Contributors
3
Replies
16
Views
2 Years
Discussion Span
Last Post by vegaseat
0

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");
1

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

if(fp==NULL);

0

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

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

is correct code

Edited by vegaseat

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.