C how to search string in a file?












1















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
    Nov 20 '18 at 21:31













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

    – usr2564301
    Nov 20 '18 at 21:35











  • 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
    Nov 20 '18 at 21:46
















1















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
    Nov 20 '18 at 21:31













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

    – usr2564301
    Nov 20 '18 at 21:35











  • 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
    Nov 20 '18 at 21:46














1












1








1








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 Nov 20 '18 at 22:09









halfer

14.6k758113




14.6k758113










asked Nov 20 '18 at 21:27









Louis HervéLouis Hervé

153




153








  • 1





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

    – yano
    Nov 20 '18 at 21:31













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

    – usr2564301
    Nov 20 '18 at 21:35











  • 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
    Nov 20 '18 at 21:46














  • 1





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

    – yano
    Nov 20 '18 at 21:31













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

    – usr2564301
    Nov 20 '18 at 21:35











  • 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
    Nov 20 '18 at 21:46








1




1





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

– yano
Nov 20 '18 at 21:31







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

– yano
Nov 20 '18 at 21:31















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

– usr2564301
Nov 20 '18 at 21:35





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

– usr2564301
Nov 20 '18 at 21:35













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
Nov 20 '18 at 21:46





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
Nov 20 '18 at 21:46












1 Answer
1






active

oldest

votes


















1














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")] = ''; // 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',
    autoActivateHeartbeat: false,
    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









    1














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





    share|improve this answer






























      1














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





      share|improve this answer




























        1












        1








        1







        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")] = ''; // 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 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")] = ''; // 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 Nov 22 '18 at 6:58

























        answered Nov 20 '18 at 21:49









        chqrliechqrlie

        60.2k747102




        60.2k747102
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            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







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()