Louis Hervé
Louis Hervé

Reputation: 53

C how to search string in a file?

I have a problem with my code, I'm trying to search a string in a file and I can read it but, when I compare two strings it takes only the last one of the file as equal to the the first string entered with the scanf().

So imagine I wrote in my file three words and each one is returning to the line.

test
test12
test123

If in my scanf() I write test12 for example or test when it's going to read it will return false to the compare so (!== 0). But if I write test123 it will works because it's the last word of the file but I don't know why?

char word[26];
char singleLine[26];
FILE *file = fopen("bin/Release/myWords.txt", "a+");

scanf("%26s", word);

if (file != NULL) {
    while (!feof(file)) {
        fgets(singleLine, 26, file);

        compare = strcmp(singleLine, word);
        if (compare == 0) {
            printf("\n%s\n",word);
        }
    }
    fclose(file);
}

Upvotes: 1

Views: 110

Answers (1)

chqrlie
chqrlie

Reputation: 144695

Your program only works in very special cases and has several problems:

  • scanf("%26s", word); may affect up to 27 bytes in the destination array, which is defined with a length of only 26.
  • furthermore, you should check the return value to avoid undefined behavior on invalid input.
  • fopen("bin/Release/myWords.txt", "a+"); opens the file in append mode: is this necessary?
  • while (!feof(file)) is always wrong, you should instead check the return value of fgets() that returns NULL at end of file.
  • compare = strcmp(singleLine, word); only compares for an exact math of the full line, which can only happen if the word has 25 characters, otherwise the trailing newline in singleLine will cause the comparison to fail. Furthermore, broken lines may cause unexpected results, as well as if the file does not end with a newline.
  • the reason it matches the last word in the file is you forget to write a trailing newline after the last word in the file, so the last fgets() fills the buffer with the exact word and no trailing newline.
  • if you search for matches inside the line, you should use a larger buffer and search for a match with strstr.
  • if you search for a exact match, you should strip the trailing newline before the comparison.

Here is a modified version:

#include <stdio.h>
#include <string.h>

int main() {
    char word[27];
    char singleLine[256];
    FILE *file = fopen("bin/Release/myWords.txt", "r");

    if (scanf("%26s", word) != 1)
        return 1;

    if (file != NULL) {
        while (fgets(singleLine, sizeof singleLine, file)) {
            singleLine[strcspn(singleLine, "\n")] = '\0'; // strip the newline if any
            compare = strcmp(singleLine, word);
            if (compare == 0) {
                printf("\n%s\n", word);
            }
        }
        fclose(file);
    }
    return 0;
}

Upvotes: 1

Related Questions