0

I wrote a c program to count the number of time the word "printf" occurs in a specific file (here "document.c"). "document.c" has multiple lines of code. What I have done is I started with a while loop to iterate over every lines of the file and then I am reading the characters of each lines inside the for loop by using the function strstr.

It does not print anything with my current code. Moreove, I think there is some other minor issues because in an older version it used to print but not correctly, it printed a number much more larger than the actual number of "printf" in the document.

I am also novice in c.thank you!

int counter() {
    FILE * filePointer;
    filePointer = fopen("document.c", "r");
    int counter = 0;
    char singleLine[200];

    while(!feof(filePointer)){
        fgets(singleLine, 200, filePointer);
        for (int i = 0; i < strlen(singleLine); i++){
            if(strstr(singleLine, "printf")){
                counter++;
            }
        }
    }
    fclose(filePointer);
    printf("%d",counter);
    return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • https://stackoverflow.com/q/5431941/3185968 also, the `for`-loop is wrong and could count the same occurrence of `printf` multiple times. – EOF Mar 15 '19 at 22:52
  • Why do you loop over a string when using `strstr` (that uses the whole string)? – raina77ow Mar 15 '19 at 22:53
  • @raina77ow In case a single line contains multiple `printf`s, but it's obviously wrong. A sane approach would use the result of `strstr()`. – EOF Mar 15 '19 at 22:57
  • Exactly. One should at least supply it with different pointer (so that search will continue from the character immediately following `printf`. – raina77ow Mar 15 '19 at 22:59
  • Thank you guys for those comments, I am reading the post about the while loop now. So I can actually get ride of the for loop? I thought that the while loop was iterative over every lines and then the for was iterating over every characters of the string. Yeah, now it actually makes sense to get ride of the for loop – freshmanUCI- Mar 15 '19 at 23:04

1 Answers1

1

You're iterating over each character in the input line, and then asking if the string "printf" appears anywhere in the line. If the line contains 5 characters, you'll ask this 5 times; if it contains 40 characters, you'll ask this 40 times.

Assuming that you're trying to cover the case where "printf" can appear more than once on the line, look up what strstr() returns, and use that to adjust the starting position of the search in the inner loop (which shouldn't iterate over each character, but should loop while new "hits" are found).

(Note to up-voters: I'm answering the question, but not providing code because I don't want to do their homework for them.)

LarryM
  • 21
  • 1