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:
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...
Just swap the conversion specifications in your format string
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")
Have a look at this,
strtok
function is what we needed. You may tell to function where to split the string with parameters, likestrtok (singleLine," ,'(");
. Here it will cut every time it see white space "," " ' " and (.strtok (singleLine," ");
or just in white spaces.