无法从当前位置向后方向使用fseek()

时间:2014-11-16 06:54:28

标签: c windows fseek

我在文件内容中搜索一个字符串,并将整个内容存储在buff char []中,排除空格' '最后将此buff char []与用户输入字符串进行比较,以检查可用性。

但是我无法存储整个文件内容,因为fgetc()正在检查if条件中的空格并放置到下一个char,即使我尝试使用fseek()指向后面的1个字符从目前的位置;它使我的程序终止。

请帮帮我;我的代码如下:

#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 个答案:

答案 0 :(得分:0)

使用整数值(如-1)的Fseek仅适用于二进制文件。 Source

尝试使用“rb”而不是“r”

进行fopen

答案 1 :(得分:0)

出于您的目的,似乎没有任何理由使用fseek

改变这个:

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

对此:

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

当然,为了安全地使用strcmp,您必须使用空字符终止buff

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

因此,请注意,对于没有空格字符的文件,您需要char buff[file_size+1]