Search code examples
cfileioembeddedspi

File I/O program in C: Segmention Fault (core dumped)


I was writing a program to read hexcodes from a file and feed it to another chip via SPI. I am trying to read each line from the hexfile using fgets and then parse it using sscanf into a unsinged int array The format of the hexfile is as follows:

ff32
34dc
1234
32d4

....

int main (void)
{
    FILE *fp1;
    int i = 0;
    fp1 = fopen("hexfile.txt", "r+");
    char line[500];
    unsigned int hex[40];

    while (fgets(line, sizeof(line), fp1) != NULL) {

        while (sscanf(line, "%x", &hex[i]) == 1) {
                    printf("%4x \n", hex[i]);
                    i++;
            }
    }

    fclose(fp1);
    return 0;
}

Error: Segmentation Fault (core dumped) Which I know roughly results when you try to dereference a NULL pointer. But what is wrong with my code? Second, is there a better way to read from a file using other File I/O functions without dynamic memory allocation?


Solution

  • You need to remove the while and replace it with if:

    FILE *fp1;
    int i = 0;
    fp1 = fopen("d:\hexfile.txt", "r+");
    char line[500];
    unsigned int hex[40];
    
    while (fgets(line, 8, fp1) != NULL) {
        if (sscanf(line, "%x", &hex[i]) == 1) {  /*here while => if */ 
            printf("%4x \n", hex[i]);
            i++;
        }
    }
    
    fclose(fp1);