Unable to use fseek() in backward direction from the current position

1k views Asked by At

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");
    }
}
2

There are 2 answers

0
barak manos On BEST ANSWER

For your purpose, there doesn't seem to be any reason to use fseek.

Change this:

if (fgetc(file) != ' ')
{
    fseek(file,-1,SEEK_CUR);
    buff[temp] = fgetc(file);
    temp++;
}

To this:

    buff[temp] = fgetc(file);
    if (buff[temp] != ' ')
        temp++;

And of course, in order to use strcmp safely, you must terminate buff with a null-character:

buff[temp] = 0;
if (strcmp(user_input,buff) == 0)
...

Hence, please note that for a file with no space characters you will need char buff[file_size+1].

0
Ben On

Fseek with integer values like -1 only work on binary files. Source

Try fopen with "rb" instead of just "r"