C-使用文件中的引号读取特定字符串

时间:2017-05-05 07:39:41

标签: c file

我正在尝试从文件中读取字符串。文件包含以下文字:

<1a>This is line 1<1a>
<2f>This is line 2<2f>
<3c>This is line 3<3c>

在我的计划中,我获得了此值1a2f。基于此,我需要像2f那样提取特定行,我只需要读取This is line 2并将其保存在缓冲区中。

我已经能够使用fopen fput阅读写作,但不知道如何阅读。任何人都可以指出一些正确的方向,说明如何阅读。任何演示代码。感谢。

2 个答案:

答案 0 :(得分:0)

char* returnSpecificString(char* valueBetweenQuotes)
{
  FILE* file= fopen("test.txt", "r"); // Open in reading only mode
  char *line= malloc(sizeof(char[150]));
  if (NULL == line) // Checks if enough memory
    fprintf(stderr, "Not enough memory. \n");
  else
  {
    while(fgets(line, sizeof(line), file)) //Iterate until end of file
    {
       if (strstr(line, valueBetweenQuotes) != NULL) // Meaning it's the line we want
       return functionToExtractTextBetweenQuote();
    }
  }
  return line;
}

至于functionToExtractTextBetweenQuote()我建议您查看strtok() strchr()sprintf()等功能,这些功能可帮助您从字符串中提取所需内容。我知道这是不合适的,但我现在没有时间完成它,所以我希望它能帮到你。

答案 1 :(得分:0)

这应该可以解决问题:

#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;
}

基本上,您需要做的是获取标记字段并将其用作分隔符来提取标记。只需获取行标记,然后使用它来提取数据。