how to detect a particular string in a file using C program

不羁岁月 提交于 2019-12-02 08:13:06

If the format is 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");
}

Repeat the above if until end of file.

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

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("A.C","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();
}

This sounds a bit like homework but here's a basic strategy that should help.

You basically just want to parse the file as text. Iteratively find the index of string "nalu_type=" and then get a substring of what comes after that. The part you are missing is what delimits the value x. You would need to know what the end-delimiter is at least.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!