skip to Main Content

I keep running in to this issue when trying to read any data from a file (the files first line does contain a number). To do this I used

fscanf(Read_File, "%d", &Number);

This is my full code

#include <stdio.h>
#include <string.h>

int main (void)
{
    char Name[50] = "Test";
    int Number = 5;
    
    FILE* Read_File;
    
    Read_File = fopen("Employee Details.txt", "r");
    
    fscanf(Read_File, "%d", &Number);
    
    printf("%d", Number);
    
    //puts(Name);
}

Each time I try and run this though I get the error in the image bellow.
Image Or Error EXC_BAD_ACCESS

This is something that I have done before when using Visual Studio but that dosent seem to be available for Mac, and since I switched recently Xcode seems to be my best bet.

2

Answers


  1. Your code seems to be fine per testing on my side. It is highly likely that your program does not find your file during run time — hence throwing the EXC_BAD_ACCESS exception — because the code tries to read from a stream that is actually not available to the program.

    Here is your code, adjusted to 1.) only attempt file read if the file is found and opened, and 2.) alert the user if the file failed to open.

    #include <stdio.h>
    
    int main ()
    {
        int number = 5;
        FILE* read_file;
        
        read_file = fopen("Employee Details.txt", "r");
        if(read_file)  /* Added:  ensure file pointer not NULL */
        {
            fscanf(read_file, "%d", &number);
            printf("%dn", number);
        }
        else
        {   /* Execution comes here if file failed to open. */
            printf("File open failed!n");
        }
        return 0;
    }
    
    Login or Signup to reply.
  2. The default assumption for this sort of crash is a memory management error. In this case, it seems that the program was unable to find the file, which resulted in fopen() returning a null pointer, which was later passed to fscanf(), and hence undefined behaviour was invoked. Consider:

    #if 0
        Read_File = fopen("Employee Details.txt", "r");
    #else
        #include <errno.h>
       
        Read_File = (errno = 0, fopen("Employee Details.txt", "r"));
        
        if (!Read_File) {
            errno ? perror("fopen()") : (void) fputs( /* Error message. */, stderr);
            /* Handle error here. */
        }
    
        /* Safe to use the pointer now. */
    #endif
    

    Also consider checking the return value of fscanf().

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search