简体   繁体   中英

Parsing file txt C

I guys i've this part of my code:

void token(){
FILE *pointer;
user record;
pointer = fopen("utente_da_file.txt","r+");
printf("OK");   
fscanf(pointer , "%s, %s, %s, %s, %s \n" , record.nome_utente , record.nome , record.cognome , record.data_di_nascita , record.data_di_iscrizione);
fclose(pointer);
printf("TEXT -> %s \n" , record.nome_utente);
}

This is utente_da_file.txt

cocco,ananas,banana,ciao,miao 

This is my output:

TEXT -> cocco,ananas,banana,ciao,miao 

I don't understand why. Greetings :)

This is due to the nature of %s parameter in scanf family: it consumes all characters up to the first white space character it encounters – or up to the end of input, whichever comes first ( scanf - OK, C++ documentation, but applies for C alike). As you do not have any whitespace in your file, the entire content is consumed at once, including the commas, before you can scan for them in your format string...

You would get a hint for if you checked the return value of (f)scanf - it returns the number of variables filled, so you should have got 1 as return value.

Problem with (f)scanf family is that you cannot specify the delimiters for your strings to stop. So in your case, you will have to append white space in between the words of the file. But be aware that the comma will be part of the string then, if you append whitespace after them, you would have to append whitespace before so that your format string can consume them - this might make your file ugly, though, so you might prefer dropping it entirely then (but then drop them in the format string, too!).

Alternatively, you can read the entire line at once using fgets and then parse it using strtok . The whole procedure could look similar to the following piece of code:

char buffer[256];
fgets(buffer, sizeof(buffer), pointer);
char const* delimiters = ", \t\n\r";
char* token = strtok(buffer, delimiters);
if(token)
{
    strncpy(record.nome_utente, token, sizeof(record.nome_utente));
    if((token = strtok(NULL, delimiters)))
    {
        strncpy(record.nome, token, sizeof(record.nome));
        // rest alike...
    }
}

for me the best solution is to write thr C code in this way (a space between 2 %s):

fscanf(pointer , "%s %s %s %s %s \n" , record.nome_utente , record.nome , record.cognome , record.data_di_nascita , record.data_di_iscrizione);

and write your text file in this way (a space between two records):

cocco ananas banana ciao miao

In this way I'm sure it works well. Ciao e buona fortuna.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM