gpt4 book ai didi

c - 如何在文件中查找字符串?

转载 作者:太空宇宙 更新时间:2023-11-04 07:07:12 25 4
gpt4 key购买 nike

我是 C 语言的新手,最近完成了我的文件工作。我试图创建一个程序来查找文件中输入的名称,但它不起作用。你能尝试修复它吗?我会很感激。

#include <stdio.h>
#include <string.h>

int main()
{
FILE *fr;
int i,p,counter,final,length,j,c,k = 0;
char name[256];
char buffer[1024];

fr = fopen("C:/Users/prixi/Desktop/HESLA.TXT","r");
while ((c = fgetc(fr)) != EOF)
counter++;

printf("Enter the name");
scanf("%s",&name);
length = strlen(name);

while (fscanf(fr, " %1023[^\n]", buffer) != EOF) {
for (i = 0; i <= counter; i++)
if (name[0] == buffer[i]){
for (j = 0;j < length; j++ )
if (name[j] == buffer[i+j])
p++;
else
p = 0;

/* The 2nd condition is there because after every name there is ' '. */
if (p == length && buffer[i+j+1] == ' ')
final = 1;
}
}

if ( final == 1 )
printf("its there");
else
printf("its not there");
return 0;
}

它将文件的内部加载到缓冲区,然后根据文件的长度逐个字符地扫描。我知道它效率低且速度慢,但我只学习 C 大约 4 天。我真的很希望你帮我修复我自己的代码,否则 :D 我可能无法休眠。

最佳答案

有很多方法可以将字符串搜索到文件中。试试这个:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

char *loadFile(const char *fileName);

int main (void) {
const char *fileName = "test.txt";
const char *stringToSearch = "Addams";
char *fileContent = loadFile(fileName);

if (strstr(fileContent, stringToSearch)){
printf("%s was Found\n",stringToSearch);
}else{
printf("%s was not Found\n",stringToSearch);
}

free(fileContent);

return 0;
}

char *loadFile(const char *fileName){
size_t length,size;
char *buffer;
FILE *file;

file = fopen (fileName , "r" );
if (file == NULL){
printf("Error fopen, please check the file\t%s\n",fileName);
exit(EXIT_FAILURE);
}


fseek (file , 0 , SEEK_END);
length = (size_t)ftell (file);
fseek (file , 0 , SEEK_SET);

buffer = malloc(length+1);
if (buffer == NULL){
fputs ("Memory error",stderr);
exit (2);
}

size = fread (buffer,1,length,file);
if (size != length){
fputs ("Reading error",stderr);
exit(3);
}
buffer[length] = '\0';

fclose (file);
return buffer;
}

输出:

Addams was Found

我在文件“test.txt”中有以下内容:

Michael Jackson
Bryan Addams
Jack Sparrow

关于c - 如何在文件中查找字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31706374/

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