Search code examples
ctext-filesfilestream

Reading from a textfile in a certain format


I am trying to read from file in this order: 0 0 4 (100) 12 (67) 2

this correspondes to:

process id, arrival_time, 1st_CPU_burst, (1st_IO_burst), 2nd_CPU_burst, (2nd_IO_burst)

This has something to do with operating system fundamentals I am trying to perform fcfs scheduling with a queue but before I do that I have to read correctly.

In my code I am trying to only read numbers with brackets around them and print the same input such as (200) but it does not work because it doesnt recognize the brackets. This is for debugging purposes, but I am going to be following the format above.

Code:

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


int main(int argc, char** argv)
{
    char input;
    char b1;
    char b2;
    FILE *f = fopen("CPULoad.dat", "r");

     while(fscanf(f, "%s%s%s", &b1, &input, &b2) == 1)
     {


        printf("%s%s%s", &b1, &input, &b2);

      }
 return 0; 
}

Solution

  • IMO, the best approach will be

    1. Read the whole line from file using fgets()
    2. Tokenize the input using "()" as delimiter.
    3. Check the token for non-NULL.
    4. use strtol() [or family] to convert the token to int or long int.

    Note; Always check for the success of fopen() before using the returned pointer.