一致文件格式中可变长度的C子串

问题描述 投票:0回答:1

我有文件中的以下行:

Name:   variable_length_string

我想提取子字符串:

variable_length_string

从它。这就是我所拥有的:

  char* getProcStatus(const char* path) {
      printf("path: %s", path);
      char* chrptr_ProcessStatus = NULL;
      FILE* fd_status = fopen (path, "rt");
      char line[300];
      char name[5];                                                                                                                                                                           
   
      char* procName = NULL;
      if ( fd_status ) {
          if (fgets(line, sizeof(line), fd_status) != NULL) {
              sscanf(line, "%s%s", name, procName);
              if (procName != NULL) {
                  printf("%s", procName);
                  fclose(fd_status);
                  return procName;
              }
          }
      }

      return procName;
  }

我尝试创建一个名称缓冲区只是为了将“Name:”存储在某处,但它根本不起作用(if(procName!= NULL))没有执行。

如何获取可变长度的子字符串?我只知道它以 ' 结尾 ' 并且该行始终以 'Next: ' 开头

c
1个回答
0
投票

我认为

sscanf (line, "%s%s", ...
不会如你所期望的那样。第一个
%s
可能会将整行加载到第一个参数中。

在下面的代码中,我搜索

:
字符,然后将指针增加到超过所有空格。
strdup
用于分配可返回的指针。其他增强功能可能是修剪行中的所有尾随空格。

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

char *
getProcStatus (const char* path) {
  FILE  * fd_status = fopen (path, "rt");
  char  line [300];
  char  * procName = NULL;
  const char  * tptr;

  printf ("path: %s\n", path);

  if ( fd_status ) {
    if (fgets (line, sizeof(line), fd_status) != NULL) {
//      sscanf (line, "%s%s", name, procName);
      tptr = strchr (line, ':');
      if (tptr == NULL) {
        fclose (fd_status);
        return NULL;
      }
      ++tptr;
      while (*tptr == ' ') {
        ++tptr;
      }
      if (*tptr == '\n' || *tptr == '\0') {
        fclose (fd_status);
        return NULL;
      }
      procName = strdup (tptr);
      size_t len = strlen (procName);
      if (len > 0 && procName [len - 1] == '\n') {
        procName [len - 1] = '\0';
      }
      printf ("procname: %s\n", procName);
    }
  }

  fclose (fd_status);
  return procName;
}

int
main (int argc, char *argv [])
{
  char    *str;

  str = getProcStatus ("zz.txt");
  if (str != NULL) {
    free (str);
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.