0

I created a program that open a file, reads the content and prints it. But, the 'fopen' returns 'NULL'. In the 'fopen', I tried with r, with a+, but nothing. The file written nella 'fopen' exist, so I don't why it returns NULL.

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <time.h>
#include <errno.h>
#include <iso646.h>
#include <stddef.h>


int main() {

FILE *fp=fopen("prova.txt", "a+");
int vett[50];
int i;

if (fp!=NULL) {
    printf("Il file è stato aperto con successo!");
    
}else{

    printf("Il file non è stato aperto con successo");
    return 0;

}

for (i = 0; !feof(fp); i++) {

    fscanf(fp, "%d", &vett[i]);
    printf("\n%d\n",vett[i]);
    
}

return 0;

}

Can you help me?

AntonelloP
  • 29
  • 4
  • You can print `errno` to see what the reason is. Maybe you don't have permission? You forgot to close the file. – Devolus Apr 21 '21 at 15:55
  • 1
    My psychic powers suggest that `prova.txt` is not in the current working directory. Run your program from the command line instead of the IDE. And make sure your current directory has both the executable and the text file in it. – selbie Apr 21 '21 at 15:55
  • 1
    @selbie, open mode `a+` should create the file if it doesn't exist. – Devolus Apr 21 '21 at 15:56
  • [That for loop is wrong](https://stackoverflow.com/q/5431941/6699433) – klutt Apr 21 '21 at 16:01
  • The pointer is not null, i printed it and it works fine . the issue starts from your for loop – Saifeddine Ben Salem Apr 21 '21 at 16:21
  • You should close the file in the program use fclose(fp) the problem is i think Maybe you didn't close the file make sure you close it , maybe the file damaged or you don't have the access to the file – WalidKhaddoum Apr 21 '21 at 16:01

2 Answers2

0

Use an absolute path for the prova.txt file. Relative paths are meaningless unless you know what the current working directory is, and to know that you'd need to print it out. Use getcwd, for example, to obtain current working directory. It likely won't be what you think it is.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
0

If fopen returns NULL, the file could not be opened (most of the time because it doesn't exist). Ensure the file is in the same directory as the executable.

You want to read from the file, therefore you should open it with the "r" mode.

And your loop is wrong, you probably want this:

for (i = 0; i < sizeof(vett)/sizeof(vett[0]); i++) {

    if (fscanf(fp, "%d", &vett[i]) == EOF)
      break;

    printf("\n%d\n",vett[i]);        
}

Note: sizeof(vett)/sizeof(vett[0]) is the number of elements of the vett array (50 in this case).

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115