I extracted part of the "value" of my code (and also replaced some string to simplify it).
I have 2 dynamic pointers, one for the current line (extracted from the file) and the second for the current token. After this question, delete / delete the strtok_r pointer before processing the full line? I wrote this:
int main(void) { int n = 455; char *tok2, *freetok2; char *line, *freeline; line = freeline = malloc(n*sizeof(*line)); tok2 = freetok2 = malloc(n*sizeof(*tok2)); const char* file_reading = "coucou/gniagnia/puet/"; strcpy(line, file_reading); strtok(line, "/"); tok2 = strtok(NULL, "/"); fprintf(stdout, "%s \n", tok2);
But in the end, I'm not sure what is right or not, and I find this solution not very elegant (due to the use of 2 "save variables".
It is right? Is there any way to improve it? Thanks
Edit: changed my code for this (and it will process all lines of the file)
include <unistd.h> include <stdlib.h> int main(void) { char *tok2; char *line; const char* file_reading = "coucou/gniagnia/puet/"; const char* file_reading2 = "blabla/dadada/"; line = strdup(file_reading); strtok(line, "/"); tok2 = strtok(NULL, "/"); printf("%s \n", tok2); printf("%s \n", line); line = strdup(file_reading2); strtok(line, "/"); tok2 = strtok(NULL, "/"); printf("%s \n", tok2); printf("%s \n", line); free(line); return 0; }
source share