如何在c中搜索文本文件中的特定字符串
我需要从文本文件的内容中找到一个特定的字符串。用户输入要查找的字符串,程序在打开的文本文件中搜索该字符串。使用C语言可以吗 这是应使用以下功能展开的基本代码:如何在c中搜索文本文件中的特定字符串,c,string,text-files,file-handling,C,String,Text Files,File Handling,我需要从文本文件的内容中找到一个特定的字符串。用户输入要查找的字符串,程序在打开的文本文件中搜索该字符串。使用C语言可以吗 这是应使用以下功能展开的基本代码: void exam() { char name[50], rollno[50]; FILE *search; printf("\t\t________________________________"); printf("\n\n\t\t\tPortal Examination"); printf("\n\t\t_____________
void exam()
{
char name[50], rollno[50];
FILE *search;
printf("\t\t________________________________");
printf("\n\n\t\t\tPortal Examination");
printf("\n\t\t_______________________________");
printf("\n\tEnter Name : ");
scanf("%s", name);
search = fopen("Students.txt", "r");
}
当然。事实上,这正是我所举的一个例子: 将文件(部分)读入内存,然后使用标准字符串 函数来搜索 字符串(在循环中)。-pmg
将(部分)文件读入内存,然后使用标准字符串函数(在循环中)搜索字符串。好的,我们开始…'我已经搜索过这个网站和其他很多网站,但没有人回答我的问题-请发布你使用的谷歌搜索字符串和你找到的几个链接。@Magisch waiting是一个盾牌计划,以避免任何“无益和敌对”的元攻击。可能重复@MartinJames。不幸的是,对这个问题是由一个似乎不了解过程式/命令式编程语言中的重复结构的人写的。
void find_match(FILE *input_file, char const *needle, size_t needle_size) {
char input_array[needle_size];
size_t sz = fread(input_array, 1, needle_size, input_file);
if (sz != needle_size) {
// No matches possible
return;
}
setvbuf(input_file, NULL, _IOFBF, BUFSIZ);
unsigned long long pos = 0;
for (;;) {
size_t cursor = pos % needle_size;
int tail_compare = memcmp(input_array, needle + needle_size - cursor, cursor),
head_compare = memcmp(input_array + cursor, needle, needle_size - cursor);
if (head_compare == 0 && tail_compare == 0) {
printf("Match found at offset %llu\n", pos);
}
int c = fgetc(input_file);
if (c == EOF) {
break;
}
input_array[cursor] = c;
pos++;
}
}
…
search = fopen("Students.txt", "r");
if (!search) { perror("Students.txt"); return; }
char line[4095+1];
while (fgets(line, sizeof line, search))
if (strstr(line, name)) printf("%s", line);
fclose(search);
}