-1

So I tried to open and read a file this way but I get:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x68) it says that the pointer is null

This is my code:

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

int main(int argc, const char * argv[]) {
    
    FILE * fp;
    
    fp = fopen("labb.txt", "r");
    
    char line[200];
    
    while(!feof(fp)){
       
            fgets(line, 200, fp);
            puts(line);
        
        
    }fclose(fp);
    
    return 0;
}
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128

1 Answers1

1

I see at least three problems in your code:

  1. This is not going to work:

    fp = fopen(fileLocation, "r"); // fileLocation is "~/Desktop/labb.txt"
    

    The C library stdio functions do not know what ~ is. It's not going to expand ~ for you. You should expand it yourself or change method. See this post for more information.

    If the file is in the same directory as the one you are running the program in, you can use ./labb.txt. If not, you can always use the absolute path to the file, or figure out a correct relative path. E.G. if labb.txt is in /home/you/Desktop and your program is in /home/you you should use ./Desktop/labb.txt.

  2. You do not check for errors. You should check fp != NULL after the call to fopen. Opening a file can always fail, always check for errors.

    fp = fopen(...);
    if (fp == NULL) {
        perror("fopen failed");
        return 1;
    }
    

    The same goes for fgets, reading a file can always fail.

    char *res = fgets(line, 200, fp);
    if (res == NULL) {
        perror("fgets failed");
        return 1;
    }
    
  3. while (!feof(fp)) is always wrong: see this answer to understand why.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128