【问题标题】:how to detect a particular string in a file using C program如何使用C程序检测文件中的特定字符串
【发布时间】:2011-03-14 06:08:15
【问题描述】:

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

提前致谢 卫生巾

【问题讨论】:

    标签: c string file compare


    【解决方案1】:
    # 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();
    }
    

    【讨论】:

    • 您是否正在检查文件内第一个字符串中给定字符串的出现?我想这被跳过了。
    【解决方案2】:

    如果格式是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");
    }
    

    如果直到文件结束,重复上述操作。

    【讨论】:

    • 我遇到分段错误。你能详细描述一下你的答案吗?
    • @sunmoon - 你在= 符号周围添加了空格。最初的问题没有它们。 strstr 可能是没有空格的更好选择。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-10-30
      • 1970-01-01
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      相关资源
      最近更新 更多