Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
527 views
in Technique[技术] by (71.8m points)

c - read consecutive tabs as empty field fscanf

I have a file that has certain fields separated by tabs. There will always be 12 tabs in a line, certain tabs are consecutive which indicates an empty field. I wanna use fscanf to read consecutive tabs as empty fields and store them in a structure. But there seems to be a problem. This is my file:

   usrid    User Id 0   15  string  d   k   y   y           0   0

When I tried to read using fscanf, tab after tab is not recognized as an empty field and data are stored in the wrong structure fields. What is the best way to deal with is issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

fscanf is a non-starter. The only way to read empty fields would be to use "%c" to read delimiters (and that would require you to know which fields were empty beforehand -- not very useful) Otherwise, depending on the format specifier used, fscanf would simply consume the tabs as leading whitespace or experience a matching failure or input failure.

Continuing from the comment, in order to tokenize based on delimiters that may separate empty fields, you will need to use strsep as strtok will consider consecutive delimiters as one.

While your string is a bit unclear where the tabs are located, a short example of tokenizing with strsep could be as follows. Note that strsep takes a pointer-to-pointer as its first argument, e.g.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (void) {

    int n = 0;
    const char *delim = "
";
    char *s = strdup ("usridUser Id 015stringdkyy00"),
        *toks = s,   /* tokenize with separate pointer to preserve s */
        *p;

    while ((p = strsep (&toks, delim)))
        printf ("token[%2d]: '%s'
", n++ + 1, p);

    free (s);
}

(note: since strsep will modify the address held by the string pointer, you need to preserve a pointer to the beginning of s so it can be freed when no longer needed -- thanks JL)

Example Use/Output

$ ./bin/strtok_tab
token[ 1]: 'usrid'
token[ 2]: 'User Id 0'
token[ 3]: '15'
token[ 4]: 'string'
token[ 5]: 'd'
token[ 6]: 'k'
token[ 7]: 'y'
token[ 8]: 'y'
token[ 9]: ''
token[10]: ''
token[11]: '0'
token[12]: '0'

Look things over and let me know if you have further questions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...