1

What I am doing -

I am trying to read a file that contains information about processes and create 3 different arrays. One for array name, second for arrival time and third for process time and compute it afterwards. The number of processes are not fixed but for testing purposes I am keeping it to 4 processes.

The first printf line outputs what I desire. The file contents in the form of array.

void readFile() {

int i = 0;
char printLine[10];
char *processName[4];
char *arrivalTime[4];
char *processTime[4];

FILE *processFile = fopen("processes.txt", "r");

while(!feof(processFile)){ 

       fgets(printLine, 10, processFile); // get the line

       processName[i] = strtok(printLine, " ");
       arrivalTime[i] = strtok(NULL, " ");
       processTime[i] = strtok(NULL, "");
       printf("%s %s %s\n", processName[i], arrivalTime[i], processTime[i]);

       i++;       
}

printf("----\n%s %s %s\n", processName[0], arrivalTime[0], processTime[0]);
}

Error - The error(sort of) is that the output of 2nd print line gives me the last process information even though I am printing the 1st element(1st process) information. So, instead of printing 1st element it is printing the last.

processes.txt file looks like this

P1 0 3
P2 1 6
P3 4 4
P4 6 2

P.S. The format of this file will be fixed so no issue there.

I am a real real novice in this. Please excuse my silliness.

EDIT - my output

output image

BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70

1 Answers1

1

This is because of the way strtok works, it doesn't return a pointer to a copy of the token, it returns a pointer to the first character of the token in the ORIGINAL location. You need to create a copy yourself.

basically, after the first read you have the following situation:


[ 1^'P','1','\0',2^'0','\0',3^'3','\0']

1: printLine,processName[0]
2: arrivalTime[0]
3: processTime[0]


  • So printLine and processName[0] are just pointing at the first position -marked by 1^-.

  • arrivalTime[0] is just pointing at the 4th position -marked by 2^-.

  • processTime[0] is just pointing at the 6th position -marked by 3^-.

Where basically all you "string"s -which are actually just character pointers- are pointing to different points within the same sequence of characters. When you read the new string, it overwrite the old data, but the pointers stay where they are.

After your loop is done you have the following situation:


[ 1^'P','4','\0',2^'6','\0',3^'2','\0']

1:printLine,processName[0],processName[1],processName[2],processName[3] 2:arrivalTime[0],arrivalTime[1],arrivalTime[2],arrivalTime[3] 3:processTime[0],processTime[1],processTime[2],processTime[3]


As you can see, everything is just pointing at different places in the same sequence of characters.

hassan arafat
  • 657
  • 5
  • 15