gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:25:53 25 4
gpt4 key购买 nike

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

但是我无法存储整个文件内容,因为 fgetc() 正在检查 if 条件中的空格并放置到下一个字符,即使我尝试使用 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");
}
}

最佳答案

就您的目的而言,似乎没有任何理由使用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]

关于c - 无法从当前位置向后使用 fseek(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26954642/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com