Dongilica
Dongilica

Reputation: 73

How to compare string from file and stdin string

I need to make program that checks if string inputted from console matches any string from input file and in my case it only works if i enter string that's last line in input file and i dont know why

int n;
char c[20];
char broj[20];
FILE* input;
input =  fopen("input.txt", "r");
scanf("%s", broj);

while(fgets(c, 200, input) != NULL)
{
    if(strcmp(c, broj) == 0)
        printf("%s", c);
} 
printf("\n");
fclose(input);

return 0;

Upvotes: 0

Views: 724

Answers (1)

Calum A
Calum A

Reputation: 65

As some have pointed out, you are reading too much into your buffer.

I really do not like to see the use of sizeof operator when calculating buffer sizes as the results can change depending on context.

void printSizeofTest1(char *test1) {
   printf("Size of test1: %d\n", sizeof(test1));
}

int main() {
   char *test = NULL;
   char test1[10] = { 0 };
   char test2 = '\0';
   printf("Size of test: %d\n", sizeof(test));
   printf("Size of test1: %d\n", sizeof(test1));
   printf("Size of test2: %d\n", sizeof(test2));
   printSizeofTest1(test1);
   return 0;
}

Size of test: 4
Size of test1: 10
Size of test1: 1
Size of test1: 4

And you see this often when copying and pasting code.

Instead, it's far better to define the length of your pointers as macro expressions and always add a NULL byte pad for signed chars. And never reference it via sizeof but via the macro. This also means that if you need to change the size of the buffer, you only need to change it in one place.

With regards to your question. It's difficult without seeing the input file, however, when you use fgets it's going to pull back any new line ending characters, which may not necessary represent your input.

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

#define BUFF_SIZE 20

int main() {
    char c[BUFF_SIZE+1]    = { 0 },
         broj[BUFF_SIZE+1] = { 0 };

    FILE *input = fopen("input.txt", "r");

    if(NULL != input) { /* <- Test for NULL file pointer */
        scanf("%20s", broj); /* <- Provide a width specifier to avoid buffer overflow */

        while(fgets(c, BUFF_SIZE, input) != NULL) {
            printf("Searching for: %s\nFound: %s\n", broj, c);
            if(strcmp(c, broj) == 0)
                printf("%s", c);

            memset(c, '\0', BUFF_SIZE); /* <- Clear buffer to ensure consistent search results */
        }

        fclose(input);
        input = NULL; /* <- Assign to NULL so that you can check to see if it's closed */
    }
    printf("\n");

    return 0;
}

In this example, I never find the contents of my file because my search is looking for a new line character which does not exist in my search string.

Instead, you should:

  • Remove the new line encodings from the file
  • Ignore the new line encodings
  • Search for precisely what you are looking for

Upvotes: 1

Related Questions