Reputation: 53
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
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
.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.fgets()
fills the buffer with the exact word and no trailing newline.strstr
.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