views:

138

answers:

2

Hi,

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 help me and show me a way to read this way from a file, in a simple and "cleany" way?

Thank you in advance

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: 
+1  A: 
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
}

Update: Ok, here is one that just uses scanf(). Really, scanf doesn't deal well with discrete lines and you lose the option of avoiding word buffer overflow by setting the word buffer to be the same size as the line buffer, but, for what it's worth...


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
}
DigitalRoss
Thank you for your answer, I've already done with fgets, but I would like to do it also with fscanf, just to cover all the options. Teachers also say that scanf variants are more elegant ;) and also more "tricky" I guess. If someone wants to contribute, go ahead.
neverMind
+2  A: 

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")

pmg