Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read only the first word from each line?

Tags:

c

file

scanf

I've done many simple procedures, but I'm only trying to read the first word into a char word[30], from each line of a text file.

I've tried, but without success. Oh, I have to reuse that char each time I read it. (To put in an ordered list each time I read it).

Can anyone show me a way to read this way from a file, in a simple and "cleany" way?

FILE *fp;
char word[30];
fp = fopen("/myhome/Desktop/tp0_test.txt", "r");
if (fp == NULL) {
    printf("Erro ao abrir ficheiro!\n");
} else {
    while (!feof(fp)) {
        fscanf(fp,"%*[^\n]%s",word);//not working very well...
        printf("word read is: %s\n", word);
        strcpy(word,""); //is this correct?
    }
}
fclose(fp);

For example for a file that contains:

word1 word5
word2 kkk
word3 1322
word4 synsfsdfs

it prints only this:

word read is: word2
word read is: word3
word read is: word4
word read is: 
like image 453
neverMind Avatar asked Nov 08 '25 01:11

neverMind


1 Answers

Just swap the conversion specifications in your format string

        // fscanf(fp,"%*[^\n]%s",word);//not working very well...
           fscanf(fp,"%s%*[^\n]",word);

Read the first word and ignore the rest, rather than ignore the line and read the first word.


Edit some explanation

%s ignores whitespace, so if the input buffer has " forty two", scanf ignores the first space, copies "forty" to the destination and leaves the buffer positioned at the space before "two"

%*[^\n] ignores everything up to a newline, excluding the newline. So a buffer containing "one \n two" gets positioned at the newline after the scanf (as if it was "\n two")

like image 152
pmg Avatar answered Nov 11 '25 02:11

pmg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!