-1

I am starting to program in Visual Studio (C) and I'm simply trying to print the values in the file, one by one. I can easily do this in my Eclipse version. (Which is the exact same code). My txt file is in project folder as seen here: https://i.stack.imgur.com/vIeZR.png

The code is as follows:

#include <stdio.h>
int main(int argc, char **argv) {
    int c;
    FILE *file;
    const char* file_name = "ECG.txt";
    file = fopen(file_name, "r");
    int i = 0;
    fscanf(file, "%d", &i);
    while (!feof(file))
    {
        printf("%d ", i);
        fscanf(file, "%d", &i);
    }
    fclose(file);


    return 0;

}

When I run this, I get the error stream != nullptr how can I fix this?

Dapper
  • 59
  • 3
  • 12

1 Answers1

2

It is very likely that your program tries to load the file from the directory where your executable resides, and not from that where your source files are (as you intend). Either place the ECG.txt-file in the target directory or use absolute paths, e.g. "c:/myuser/myproject/ECG.txt";

Always check the result of fopen. If the result is NULL, then the file could not be opened (probably the reason for your runtime error). So the relevant portion of your program could loo as follows:

file = fopen(file_name, "r");
if (file) {
    int i = 0;
    while (fscanf(file, "%d", &i)==1) {
        printf("%d ", i);
    }
   fclose(file);
} else {
   printf("error opening file");
}
Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
  • This is consistent with the code working in one development environment but not in another: the files are simply in different places. I'd emphasize "Always check the result of `fopen`". – Tim Randall Sep 19 '18 at 12:56