How to read only the first word from each line?

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

I tried, but to no avail. Oh, I have to reuse this char every time I read it. (To put an ordered list every time I read it).

Can someone show me a way to read this path from a file in a simple and clean 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

he only prints this:

word read is: word2
word read is: word3
word read is: word4
word read is: 
+3
source share
3 answers

Just change the conversion options in the format bar

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

, .


% s , , " ", scanf , "" , ""

% * [^\n] , . , "\n ", scanf ( "\n two" )

+10
so ross$ expand < first.c
#include <stdio.h>

int main(void) {
  char line[1000], word[1000];

  while(fgets(line, sizeof line, stdin) != NULL) {
    word[0] = '\0';
    sscanf(line, " %s", word);
    printf("%s\n", word);
  }
  return 0;
}

so ross$ ./a.out < first.c
#include

int
char

while(fgets(line,
word[0]
sscanf(line,
printf("%s\n",
}
return
}

: , , scanf(). , scanf , , , , ...


so ross$ expand < first2.c
#include <stdio.h>

int main(void) {
  char word[1000];

  for(;;) {
    if(feof(stdin) || scanf(" %s%*[^\n]", word) == EOF)
      break;
    printf("%s\n", word);
  }
  return 0;
}

so ross$ ./a.out < first2.c
#include
int
char
for(;;)
if(feof(stdin)
break;
printf("%s\n",
}
return
}
+1

, strtok - , . , , strtok (singleLine," ,'(");. , "," " '" (. strtok (singleLine," "); .

 FILE *fPointer,*fWords,*fWordCopy;
char singleLine[150];

fPointer= fopen("words.txt","r");
fWordCopy= fopen("wordscopy.txt","a");

char * pch;
while(!feof(fPointer))
{
    fgets(singleLine,100,fPointer); 
    pch = strtok (singleLine," ,'(");
    fprintf(fWordCopy,pch);
    fprintf(fWordCopy, "\n"); 
}

fclose(fPointer);

results

0

Source: https://habr.com/ru/post/1765729/


All Articles