Pablo Ajo
Pablo Ajo

Reputation: 43

How can I capture with fscanf, in C, strings from a file separated by tabulators

For example the following text (in the file):

18[tab]Robert[tab]Nice to see you again

I want my code capture: - 18 - Robert - Nice to see you again

I tried it with fscanf(file,"%s\t",buffer) but it captured words separated by spaces

Thanks

Upvotes: 0

Views: 656

Answers (2)

Orest Hera
Orest Hera

Reputation: 6776

According to your example you may also want to skip new line characters and other special control characters. You can use scanf string conversion %[ to include wanted characters or to exclude unneeded, for example:

/* exclude only '\t' and '\n' */
fscanf(file, "%[^\t\n]", buffer);
/* include only alphanumeric characters and space */
fscanf(file, "%[0-9A-Za-z ]", buffer);
/* include all ASCII printable characters */
fscanf(file, "%[ -~]", buffer);

You also should be sure that you have enough space in buffer. If you cannot control provided input string length it makes sense to limit the maximum field width using decimal integer number. Before starting parsing the next suitable string it is possible to skip all unwanted symbols. It can be done with opposite conversion pattern and assignment suppression modifier %*:

char buffer[101]; /* +1 byte for terminating '\0' */

/* Scan loop */
{
    /* Skip all non printable control characters */
    fscanf(file, "%*[^ -~]");

    /* Read up to 100 printable characters so the buffer cannot
     * overflow. It is possible to run the following line in a loop
     * to handle case when one string does not fit into single buffer
     * checking function return value, since it will return 1
     * if at least one wanted character is found */
    fscanf(file, "%100[ -~]", buffer);

    /*
     * If scan would be performed only by the following line it is possible
     * that nothing could be read if the first character is not matching
     * fscanf(file, "%100[ -~]%*[^ -~]", buffer);
     */
}

Upvotes: 0

unwind
unwind

Reputation: 399843

Use a character set, i.e. fscanf(file, "%[^\t]\t", buffer);

The ^ means "all characters except the following".

Remember to check the return value.

Upvotes: 1

Related Questions