0

I have a file and I want to read this file using C program using file operations. Then i want to take parameters from that file. Lets say nalu_type=x. So whenever i detect the string nalu_type in that file I want to put the value x in an array which is defined by me. please tell me how to do it.

Thanks in Advance Sanket

3 Answers 3

5
# 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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Are you checking for the occurence of the given string in the first string inside the file? I guess that is being skipped.
2

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.

2 Comments

I am getting segmentation fault. Can you please describe your answer in detail?
@sunmoon - you added spaces around the = sign. The original question did not have them. strstr may be a better choice without spaces.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.