I am trying to finding a string in a file. I wrote following by modifying code snippet present in man page of getline
.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE * fp;
char * line = NULL;
char *fixed_str = "testline4";
size_t len = 0;
ssize_t read;
fp = fopen("test.txt", "r");
if (fp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, fp)) != -1) {
printf("Retrieved line of length %zu:\n", read);
printf("%s", line);
if (strcmp(fixed_str,line)==0)
printf("the match is found\n");
}
//printf("the len of string is %zu\n", strlen(fixed_str));
fclose(fp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
The problem is that result of strcmp is always false despite getline is successfully and correctly iterating over all lines in the file.
The length of fixed_str is 9 and that of equal string in file is 10 due to newline character (AM I RIGHT?). But comparing 9 chars with the help of strncmp
still produces wrong result. I also ruled out the possibilities of caps and spaces so I think I am doing something very wrong
The test.txt is as below
test line1
test line2
test line3
testline4
string1
string2
string3
first name
I tried all entries but no success
NOTE: In my actual program I have to read fixed_str
from another file