0

I get this error when trying to run round robin algorithm, and the algorithms are working perfectly fine when taking input from user. this is the code:

else if (select==2)
    {
        FILE * filehandle;
        char lyne[100];
        char *item;
        int reccount = 0;
        // open file
        filehandle = fopen("Input_Data1.txt","r");

        // Read file line by line
        while (fgets(lyne,99,filehandle))
        {
            numprocess =
            printf("%s",lyne);
            item = strtok(lyne," ");
            p[reccount].arrivetime =atoi(item);

            item = strtok(NULL," ");
            p[reccount].bursttime =atoi(item);

            reccount++;
        }
        //Close file
        fclose(filehandle);
    }

The error I get is segmentation fault (core dumped).

screen shot of the input file

I tried reading from a file execting the same result as reading from user input but I got the error showed in the image.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256

1 Answers1

0

At least these issues:

Avoid atoi(NULL)

item = strtok(lyne," "); may return NULL.
item = strtok(NULL," "); may return NULL.

I suspect the 2nd should be item = strtok(NULL," \n");

NULL == filehandle?

Open may fail.

reccount may exceed max

No need for a -1

// fgets(lyne,99,filehandle)
fgets(lyne, sizeof lyne, filehandle)

    FILE * filehandle = fopen("Input_Data1.txt","r");
    if (filehandle == NULL) {
      fprintf(stderr, "Open failed\n"); 
      return;
    }
    char lyne[100];
    int reccount = 0;

    while (reccount < reccount_n && fgets(lyne, sizeof lyne, filehandle)) {
        numprocess = printf("%s", lyne); // Unclear how OP is using numprocess
        char *item = strtok(lyne," ");
        if (item == NULL) {
          fprintf(stderr, "strtok(lyne,\" \") failed\n"); 
          return;
        }
        p[reccount].arrivetime =atoi(item);

        item = strtok(NULL," \n");
        if (item == NULL) {
          fprintf(stderr, "strtok(NULL,\" \n\") failed\n"); 
          return;
        }
        p[reccount].bursttime =atoi(item);

        reccount++;
    }
    fclose(filehandle);
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256