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
scanf("%s")stops on any space character, and you may have one in your input.while(fgets(c, 200, input) != NULL)andchar c[20];You cannot stick 200 bytes of characters into a 20 byte array. To try to do so will result in a buffer overflow and undefined behavior. Suggest changing the arrayc[]andbroj[]both be 200 bytes