Maldz
Maldz

Reputation: 33

How to save specific strings in a file to variables in C

So if for example I have a file with the following content:

STUDENTS: Three
NAME 1: Andy
NAME 2: Becky
NAME 3: Chris
TYPE: Undergrads

I would like to extract the names of the students into an array.

I have tried to implement this using fscanf, for instance this works and I can save "Three" to student struct:

fscanf(fptr, "STUDENTS: %s\n", student.count);

So I've tried some variations of this (where count is the number of lines in the file), but the names array remains empty:

int *num = NULL;
*num = 1;
int j;
for (j=0; j<count; j++) {
   if (j != 0 && j != count-1) {
       fscanf(fptr, "NAME %d: %s\n", num, student.names[j]);
       *num+=1;
   }
}

Is there a better method than fscanf, for example fseek() which I am not really familiar with. Any ideas would be appreciated, thanks.

edit:

struct Students {

  char *name;
  char *type;
  char *connections[6];

};

struct Students student;

Upvotes: 0

Views: 55

Answers (1)

Gene
Gene

Reputation: 47020

The scanf family of functions isn't great for scanning lines that have variable formats. In this case a reasonable approach is to first scan the input line as a tag and string value separated by a colon.

char tag[MAX_TAG_SIZE], value[MAX_VALUE_SIZE];
if (fscanf(f, "%[^:]: %s ", tag, value) != 2) error("bad line format");

This format string gets any series of characters other than : into tag. Then it skips a : followed by whitespace. Then it gets a non-whitespace word into value followed by skipping whitespace (including newlines). The last bit gets the input ready to scan the next tag, which is important. The biggest mistake new C programmers make with scanf is forgetting to deal correctly whitespace in the input stream.

Now you can inspect the tag to see what to do next:

if (strcmp("STUDENTS", tag) == 0) {
   ... Handle students value
} else if(strcmp("TYPE", tag) == 0) {
   ... Handle type value
} else if (strncmp("NAME", tag, 4) == 0) {
    if (sscanf(tag + 4, "%d", &name_number) != 1) error("bad name number");
    ... Handle name_number and value
} else error("unexpected tag");

Upvotes: 2

Related Questions