c - How to use fscanf to read a line to parse into variables? -
i'm trying read text file built following format in every line, example:
a/a1.txt a/b/b1.txt a/b/c/d/f/d1.txt
using fscanf
read line file, how can automatically parse line variables of *element
, *next
, each element being path section (a
, a1.txt
, b
, c
, d1.txt
, on).
my structure follows:
struct mypath { char *element; // pointer string of 1 part. mypath *next; // pointer next part - null if none. }
you better off using fgets
read entire line memory, strtok
tokenise line individual elements.
the following code shows 1 way this. first, headers , structure definintion:
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct smypath { char *element; struct smypath *next; } tmypath;
then, main function, creating empty list, getting input user (if want robust input function, see here, follows below cut down version of demonstrative purposes only):
int main(void) { char *token; tmypath *curr, *first = null, *last = null; char inputstr[1024]; // string user (removing newline @ end). printf ("enter string: "); fgets (inputstr, sizeof (inputstr), stdin); if (strlen (inputstr) > 0) if (inputstr[strlen (inputstr) - 1] == '\n') inputstr[strlen (inputstr) - 1] = '\0';
then code extract tokens , add them linked list.
// collect tokens list. token = strtok (inputstr, "/"); while (token != null) { if (last == null) { first = last = malloc (sizeof (*first)); first->element = strdup (token); first->next = null; } else { last->next = malloc (sizeof (*last)); last = last->next; last->element = strdup (token); last->next = null; } token = strtok (null, "/"); }
(keeping in mind strdup
not standard c can find a decent implementation somewhere). print out linked list show loaded properly, followed cleanup , exit:
// output list. (curr = first; curr != null; curr = curr->next) printf ("[%s]\n", curr->element); // delete list , exit. while (first != null) { curr = first; first = first->next; free (curr->element); free (curr); } return 0; }
a sample run follows:
enter string: path/to/your/file.txt [path] [to] [your] [file.txt]
i should mention that, while c++ allows leave off struct
keyword structures, c not. definition should be:
struct mypath { char *element; // pointer string of 1 part. struct mypath *next; // pointer next part - null if none. };
Comments
Post a Comment