I need to read in from a file and save values to variables based on the instruct
ID: 3914315 • Letter: I
Question
I need to read in from a file and save values to variables based on the instructions below, but I'm not sure how to go about it. Any help?
Input (Process Information): The process information will be read from an input file. The format is pid arrival_time burst_time . All of fields are integer type where pid is a unique numeric process ID, arrival_time is the time when the task arrives in the unit of milliseconds, and burst_time the is the CPU time requested by a task, in the unit of milliseconds The time unit for arrival_time, burst_time is millisecond.
Command-line Usage Examples:
myCPUScheduler input_file [FCFS|RR|MLFQ]
Input file example:
% more input.txt
PID Arrival Burst
1 0 10
2 1 9
3 2 8
4 3 7
Explanation / Answer
Assuming the language used is C, you would need to use fopen() to open the input file, fgets() to read the file line by line. To tokenize the read string in the buffer buf you need to use the function strtok() or strtok_r(). To check details about the strtok() function check the man page for the same. If you don't know how to use a man page, just type man strtok() at a unix/linux terminal. Each invocation of strtok() would return a token back to you, i.e. the first token would be pid, second would be the arival time and the third one will be the burst time. To convert the string tokens returned to you you would need to use the function atoi() or strtol(). Again check man pages for the usage of the same.
So your code segment would look something like:
fp = fopen("input_file", "r");
// error checks here
while(!feof(fp)) {
// read file line by line
s = fgets(buf, sizeof(buf), fp);
// tokenize and parse the read line
pidtok = strtrok(buf, " "); // only the first invocation for each string requires the buffer
pid = atoi(pid);
arrivaltok = strtok("", " "); // next invocation does not need the buffer
arrivaltime = atoi(arrivaltok);
bursttok = strtok("", " "); // next invocation does not need the buffer
burst = atoi(bursttok);
}