Using fscanf to read the formatted string from the file


I have a file with contents as shown below.

[John][Antony][Mathew] Australia

I need to use fscanf to read contents from file.

Output should be:

firstName = John
middleName = Antony
lastName = Mathew
Country = Australia

What is the format to be used in fscanf to get firstName, middleName, lastName and country in separate strings?

Currently fscanf(fp, "[%[^]]",firstName) gives firstName correctly.

Akin to @BLUEPIXY comment "[%[^]]][%[^]]][%[^]]] %[^\n]%*c".

Since data is certainly per line, read a line first and then parse it.

The format needed is "[%99[^]]]" which says to 1) scan '[' 2) scan up to 99 non-] char and form a string 3) scan ']'.

#define N 100
#define FMT "[%99[^]]]"
#define FMTCTY " %99[^\n]"
char firstName[N], middleName[N], lastName[N], Country[N];

char buf[4*N + 10];
while (fgets(buf, sizeof buf, fp) != NULL) {
  if (4 != sscanf(buf, FMT FMT FMT FMTCTY, firstName, middleName, lastName, Country)) {
  foo(firstName, middleName, lastName, Country);

Confident OP can form the needed output format string.