I am searching a string inside the the content of a file and storing the whole content in a buff char[] by excluding the space ' ' and at last comparing the this buff char[] with user input string for checking the availability.
But I am unable to store the whole file content because fgetc()
is checking the space in if condition and placing to the next char even though I tried to use fseek()
for pointing to the 1 char backward from the current position; it is making my program to terminate.
Please help me; my code follows:
#include <stdio.h>
#include <stdlib.h>
FILE *file;
int file_size;
int main(void) {
file= fopen("C:/Users/home/Desktop/dummy/s.txt","r");
file_exist(file);
fclose(file);
return 0;
}
void file_exist(file)
{
if(file)
{
printf("file exists\n");
content_exist(file);
}
else
{
printf("it doesnt exist\n");
}
}
void content_exist(file)
{
fseek(file,0,SEEK_END);
file_size=ftell(file);
rewind(file);
char user_input[10];
if(file_size==0)
{
printf("content does not exists\n");
}
else
{
printf("content exist\n");
printf("enter the word needs to be matched\n");
scanf("%s",&user_input);
check_string(user_input);
}
}
void check_string(user_input)
{
char buff[file_size];
int temp=0;
while(!feof(file))
{
printf("hi\n");
if(fgetc(file)!=' ')
{
fseek(file, -1,SEEK_CUR);
buff[temp]= fgetc(file);
temp++;
}
}
if(strcmp(user_input,buff)==0)
{
printf("your content matched\n");
}
else
{
printf("your content not matched\n");
}
}
For your purpose, there doesn't seem to be any reason to use
fseek
.Change this:
To this:
And of course, in order to use
strcmp
safely, you must terminatebuff
with a null-character:Hence, please note that for a file with no space characters you will need
char buff[file_size+1]
.