[Solved] C- Reading specific strings with quotes from a file


This should do the trick:

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

int extract_line (char* line, char* buffer, char* ctag)
{
  char line_buffer[255] = {0};
  char* tagStart;
  char* tagEnd;

  if( strlen(line) < (sizeof(line_buffer)/sizeof(char)) )
  {
     strcpy(line_buffer,line);
  }
  else
  {
     printf("Line size is too big.\n");
     return 1;
  }

  tagStart = strstr(line_buffer,ctag);
  if(tagStart != NULL)
  {
    tagEnd = strstr(tagStart+1,ctag);
    if(tagEnd != NULL && (tagEnd > (tagStart + strlen(ctag))))
    {
        *(tagEnd) = '\0';
        strcpy(buffer, tagStart + strlen(ctag));
        printf("%s\n",buffer);
    }
    else
    {
      printf("Could not find closing tag.\n");
      return 1; 
    }
  }
  return 0;
}


int main ()
{
  char buffer[255] = {0};
  char line_buffer[255] = {0};
  char tag[] = "<2a>";

  char* cptr;
  FILE* data;
  data = fopen ("file.txt", "r");
  if (data == NULL)
  {
       printf("\n Failed to open file!");
  }
  else {
     while(( fgets( line_buffer, 255, data )) != NULL)
     {        
        cptr = strstr(line_buffer,tag);
        if(cptr == NULL)
        {
            continue;
        }
        if(!extract_line(line_buffer,buffer,tag))
        {
           //Do the rest of processing
           puts(buffer);
           strcpy(buffer,"");
        }
     }
     fclose (data);
  }
  return 0;
}

Basicly, what you need to do is get the tag field and use it as a delimeter to exctract the token. Just get the line tag and then use it to exctract the data.

7

solved C- Reading specific strings with quotes from a file