Wednesday, 7 August 2013

C get string with spaces, of unknown length, with fgets

C get string with spaces, of unknown length, with fgets

I have a file with 1 line in it, on Linux it defaults to end with a newline
one two three four
And a similar one with
one five six four
It is guaranteed that the two words in between will never be "four". I
wrote the following, wanting to assign "two three" and "five six" to a
variable, as in this code.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool getwords(FILE *example)
{
bool result = 0;
char *words;
if(fscanf(example, "one %s four\n", words) == 1)
{
printf("captured words are %s\n", words);
if(words == "two three"
|| words == "five six")
{
puts("example words found");
}
else
{
puts("unexpected words found");
}
result = 1; //so that we know this succeeded, in some way
}
return result;
}
int main(int argc, char * argv[])
{
if(argc != 2)
{
exit(0);
}
FILE *example;
example = fopen(argv[1],"r");
printf("%x\n", getwords(example)); //we want to know the return value,
hex is okay
fclose(example);
return 0;
}
The problem is that this will print "captured words are " and then only
the first word of the two to be expected in a string. This is supposed to
support files where there could be more words than 2 in between the words
"one" and "four". How can I change my code, to get all the words in the
string between first and last word?

No comments:

Post a Comment