Question

I have a program that requires that I start from word N, hash the next N+M words (concatenated and done through another function so the original pointer is not moved), and then increment the FILE pointer that is pointing at N to the next word.

The only way I thought to do this was to increment the FILE pointer until a space is found, then increment further until we found the first character of the next word. This is necessary because the file I am reading may have multiple spaces between words which would not result in a matching string compared to a file that has the same word content but single spaces.

This method would then require ungetc() because we we would have taken from the stream the first character of the next word.

Any ideas on a different implementation or am I pretty well restricted to this method?

    while ( (c = fgetc(fileToHash) != ' ' )
        ;
    while( (c = fgetc(fileToHash)) == ' ')
        ;
    ungetc(c, fileToHash); 

No correct solution

OTHER TIPS

Yes, if you insist on using the file pointer as your index, that's pretty much what you've got. A better solution would probably be to read part or all of the file into a buffer and manipulate your pointer into the buffer, unless you intend to do random-access overwriting of the file's contents -- which is generally completely impractical with text files.

How about this.

void findWord(FILE *f, int n) {
    int c = 0;
    while (n-- > 0 && c != EOF) {
        do c = fgetc(f); while (c != EOF && !isalpha(c));
        while (c != EOF && isalpha(c)) c = fgetc(f);
    }
}

You can use fscanf to read words delimited by whitespaces. This example will read each word from standard input and print each of them on a new line:

char buf[128];
while (fscanf(stdin, "%s", buf) > 0)
    puts(buf);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top