serious_black
serious_black

Reputation: 437

Segmentation fault solution

I have a text file having info as

Emp_Id  Dept_Id
  1          1
  1          2
  1          3
  2          2
  2          4

I am trying to read this file through C with this code below :

#include "stdio.h"
#include "stdlib.h"

int main()
{
    FILE *fp;
    char line[100];
    char fname[] = "emp_dept_Id.txt";
    int emp_id, dept_id;

    // Read the file in read mode
    fp = fopen(fname, "r");

    // check if file does not exist
    if (fp == NULL)
    {
        printf("File does not exist");
        exit(-1);
    }

    while (fgets(line, 100, fp) != NULL)
    {
        printf("%s", line);
        sscanf(line, "%s %s", &emp_id, &dept_id);
        printf("%s %s", dept_id, dept_id);
    }

    fclose(fp);

    return 0;
}

While i am trying to compile the code its all fine but when running it shows the follwoing error :

Segmentation fault (core dumped)

What can be the possible solution and mistakes for my code .

thanks

P.S : I am on IBM AIX and using CC . And have no other option to move from them .

Upvotes: 0

Views: 891

Answers (3)

ajay
ajay

Reputation: 9680

Your code invokes undefined behaviour because you use the wrong conversion specifier for reading and printing integers. You should use %d instead of %s. Also, output a newline to immediately print output to the screen as stdin stream is line buffered by default. Change your while loop to

while(fgets(line, 100, fp) != NULL)
{   
    // output a newline to immediately print the output
    printf("%s\n", line);

    // change %s to %d. also space is not needed
    // between %d and %d since %d skips the leading 
    // whitespace characters
    sscanf(line, "%d%d", &emp_id, &dept_id);

    // sscanf returns the number of input items 
    // successfully matched and assigned. you should
    // check this value in case the data in the file 
    // is not in the correct format

    // output a newline to immediately print the output
    printf("%d %d\n", dept_id, dept_id);
}

Upvotes: 0

unwind
unwind

Reputation: 399703

You are trying to scan and print two integers using %s, it should be %d.

Upvotes: 2

RichieHindle
RichieHindle

Reputation: 281355

Use %d to scan and print integers:

sscanf(line, "%d %d", &emp_id, &dept_id);
printf("%d %d", dept_id,dept_id);

(You should probably be checking the return value of sscanf as well, to make sure it really did read two integers - reading the first line into integers isn't going to work.)

Upvotes: 4

Related Questions