C how to search string in a file?











up vote
1
down vote

favorite












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%sn",word);
}
}
fclose(file);
}









share|improve this question




















  • 1




    see Why is “while ( !feof (file) )” always wrong?
    – yano
    yesterday












  • fgets includes the final 'n`, so it gets compared along with the rest of your string.
    – usr2564301
    yesterday










  • you need to learn how to use the debugger and use it to see the strings being compared. Until you do this you will never be able to write code.
    – john elemans
    yesterday















up vote
1
down vote

favorite












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%sn",word);
}
}
fclose(file);
}









share|improve this question




















  • 1




    see Why is “while ( !feof (file) )” always wrong?
    – yano
    yesterday












  • fgets includes the final 'n`, so it gets compared along with the rest of your string.
    – usr2564301
    yesterday










  • you need to learn how to use the debugger and use it to see the strings being compared. Until you do this you will never be able to write code.
    – john elemans
    yesterday













up vote
1
down vote

favorite









up vote
1
down vote

favorite











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%sn",word);
}
}
fclose(file);
}









share|improve this question















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%sn",word);
}
}
fclose(file);
}






c file string-comparison






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday









halfer

14.2k757105




14.2k757105










asked yesterday









Louis Hervé

153




153








  • 1




    see Why is “while ( !feof (file) )” always wrong?
    – yano
    yesterday












  • fgets includes the final 'n`, so it gets compared along with the rest of your string.
    – usr2564301
    yesterday










  • you need to learn how to use the debugger and use it to see the strings being compared. Until you do this you will never be able to write code.
    – john elemans
    yesterday














  • 1




    see Why is “while ( !feof (file) )” always wrong?
    – yano
    yesterday












  • fgets includes the final 'n`, so it gets compared along with the rest of your string.
    – usr2564301
    yesterday










  • you need to learn how to use the debugger and use it to see the strings being compared. Until you do this you will never be able to write code.
    – john elemans
    yesterday








1




1




see Why is “while ( !feof (file) )” always wrong?
– yano
yesterday






see Why is “while ( !feof (file) )” always wrong?
– yano
yesterday














fgets includes the final 'n`, so it gets compared along with the rest of your string.
– usr2564301
yesterday




fgets includes the final 'n`, so it gets compared along with the rest of your string.
– usr2564301
yesterday












you need to learn how to use the debugger and use it to see the strings being compared. Until you do this you will never be able to write code.
– john elemans
yesterday




you need to learn how to use the debugger and use it to see the strings being compared. Until you do this you will never be able to write code.
– john elemans
yesterday












1 Answer
1






active

oldest

votes

















up vote
1
down vote



accepted










Your program only works in very special cases:





  • 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")] = ''; // strip the newline if any
compare = strcmp(singleLine, word);
if (compare == 0) {
printf("n%sn", word);
}
}
fclose(file);
}
return 0;
}





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401808%2fc-how-to-search-string-in-a-file%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    1
    down vote



    accepted










    Your program only works in very special cases:





    • 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")] = ''; // strip the newline if any
    compare = strcmp(singleLine, word);
    if (compare == 0) {
    printf("n%sn", word);
    }
    }
    fclose(file);
    }
    return 0;
    }





    share|improve this answer



























      up vote
      1
      down vote



      accepted










      Your program only works in very special cases:





      • 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")] = ''; // strip the newline if any
      compare = strcmp(singleLine, word);
      if (compare == 0) {
      printf("n%sn", word);
      }
      }
      fclose(file);
      }
      return 0;
      }





      share|improve this answer

























        up vote
        1
        down vote



        accepted







        up vote
        1
        down vote



        accepted






        Your program only works in very special cases:





        • 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")] = ''; // strip the newline if any
        compare = strcmp(singleLine, word);
        if (compare == 0) {
        printf("n%sn", word);
        }
        }
        fclose(file);
        }
        return 0;
        }





        share|improve this answer














        Your program only works in very special cases:





        • 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")] = ''; // strip the newline if any
        compare = strcmp(singleLine, word);
        if (compare == 0) {
        printf("n%sn", word);
        }
        }
        fclose(file);
        }
        return 0;
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited yesterday

























        answered yesterday









        chqrlie

        58.1k745100




        58.1k745100






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53401808%2fc-how-to-search-string-in-a-file%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Berounka

            Sphinx de Gizeh

            Different font size/position of beamer's navigation symbols template's content depending on regular/plain...