I am writing a c program to read individual lines from a file and check if any line(in this case a single word) is equal to hello.
i am using fgets function.
The length of the lines in the text file are unknown, thus i use an array variable buff that is of a considerate length.
But strcmp never returned 0. I thought that fgets was taking in extra space for the remaing length of the array so i transferred the contents of buff into another array called tmp.
Size of tmp=strlen(buff).
But i am getting a different out put.
Here is the code:
Code:
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
char buff[128];
fp=fopen("fi.txt","r");
if(fp==NULL)
{printf("HELLO \n");printf("File does not exist");}
else{printf("FILE EXISTS \n");
printf("Debugging stage loc 1==");
while(fgets(buff,sizeof buff,fp) !=NULL){
char tmp[strlen(buff)];
printf("%d tmp length=",(int)strlen(tmp));
printf("%d buff length=",(int)strlen(buff)); printf("\n");
strcpy(tmp,buff);
printf("\n");puts(buff);
puts(tmp);
printf("\n");
printf("%d",strcmp(tmp,"hello"));
printf("\n");break;
}}
return 0;
}
And here are the contents of the file:
hello
poll
And here is the output:
FILE EXISTS
Debugging stage loc 1==0 tmp length=6 buff length=
hello
hello
1
Q1) What is the 0 after debugging location 1? Where is it coming
from?
Q2) tmp length is alright but why is buff length not being displayed?
Q3) if both values are hello, then why is strcmp returning 1 and not 0?