Reputation: 491
I'm new to C and I see plenty of example of reading a file one word at a time but I'm trying to make a function that is given a line of text(actually a list of filenames) and it needs to read a word(filename) at a time.
Eg. I call the function, words("file1.c file2.c file3.txt");
And the function needs to read each word(filename) and put it through another function.
So far I've got:
void words(char* line) {
char buf[100];
while (!feof(line)) {
fscanf(line,"%s",buf);
printf("current word %s \n", buf);
}
}
But this won't compile. I get "passing argument 1 of ‘feof’ from incompatible pointer type"
edit So this is the code I've come up with. It seems to work fine if I called it with words("test1 test2 test3 test4 "); but if the last character is not a space then it has an error in the out put. eg ("test1 test2 test3 test4");
char buf[100];
int word_length = 0;
int n;
while((sscanf(line + word_length,"%s",buf, &n)) == 1) {
printf("current word %s \n", buf);
word_length = word_length + strlen(buf) + 1;
}
What I am doing wrong?
Upvotes: 3
Views: 3665
Reputation: 33273
The fscanf
and feof
functions work on files.
The corresponding function for strings is sscanf
.
The return value from sscanf
can be used to check whether you managed to scan anything from the string and how far into the string you should look for the next word.
Edit:
Good effort. There are two problems left. First, if there are multiple spaces between words your code will fail. Also, the + 1
will move you past the null terminator if there is no space after the last word.
The second problem can be solved by not adding a +1. That means that the next item will be scanned right after the previous one ends. This is not a problem because scanf
will skip initial whitespace.
The problem with multiple spaces can be solved by finding how far into the string the next token starts using strstr
.
Because strstr
returns a pointer I switched to using a pointer instead of an index to keep track of progress through the string.
char *ptr = line;
while((sscanf(ptr,"%s",buf)) == 1) {
printf("current word %s \n", buf);
ptr = strstr(ptr, buf); // Find where the current word starts.
ptr += strlen(buf); // Skip past the current word.
}
Upvotes: 4