I have the following code in which I'm reading lines from a file and want to save them using a character pointer array. As I'm using one buffer inside my file read loop all my pointers in the character array end up pointing towards the last line read from file as the last line is the one that is currently held in the buffer when the loop terminates. How can I store them such that each pointer in the character array points to different char arrays in the order they were read.
int num_clients_to_start = 0;
char *token1, *token2, *str;
FILE* fp;
char bufr[256];
char testchar[255] = {};
char *start_client[10];
while(fgets(bufr, 256, fp) != NULL){
if(bufr[0] == '#'|| bufr[0] == '\n')
continue;
str = bufr;
token2 = ""; /* initializing an empty token 2 */
for(str = bufr; ;str = NULL){
token1 = strtok(str, " ");
if(strcmp(token2, "client_name") == 0){
sprintf(testchar,"%s", token1);
start_client[num_clients_to_start] = testchar;
num_clients_to_start++;
}
token2 = token1;
if(str == NULL){
break;
}
}//end of for loop
}//end of while loop
printf("client1 = %s client2 = %s client3 = %s",start_client[0],start_client[1],start_client[2]);
My input file is the following:
client_name abc
client_name def
client_name xyz
And print statement outputs:
client1 = xyz
client2 = xyz
client3 = xyz