如何使用C程序检测文件中的特定字符串

我有一个文件,我想使用文件操作使用C程序读取此文件。 然后我想从该文件中获取参数。 让我们说nalu_type = x。 因此,每当我检测到该文件中的字符串nalu_type时,我想将值x放在由我定义的数组中。 请告诉我怎么做。

先谢谢Sanket

如果格式为nalu_type = x

fscanf(fp, "%s", buf); if !strcmp(buf, "nalu_type") { fscanf(fp, "%s", buf); if ( ! strcmp(buf, "=")) fscanf(fp, "%s", buf); else printf("\n Not a valid format"); } 

如果直到文件结尾,请重复上述步骤。

 # include # include  # include  void main() { int noc=0,l; FILE *fp; char *str2,ch; char*str1; clrscr(); printf("Enter the String to be matched\n"); gets(str1); l=strlen(str1); fp=fopen("AC","r"); while(1) { ch=fgetc(fp); if(ch==EOF) break; else if(ch==' ') { fgets(str2,l+1,fp); if((strcmp(str1,str2))==NULL) noc++; } } printf("NO of occurence is: %d",noc); getch(); } 

这听起来有点像家庭作业,但这是一个应该有所帮助的基本策略。

您基本上只想将文件解析为文本。 迭代地找到字符串“nalu_type =”的索引,然后得到之后的字符串。 您缺少的部分是界定值x的部分。 你需要知道最终分隔符是什么。