【问题标题】:sscanf: Which additional characters I have to consider in order to get to the correct value?sscanf:为了获得正确的值,我必须考虑哪些额外的字符?
【发布时间】:2021-04-26 07:42:13
【问题描述】:

这是扫描以下有关 /proc/cpuinfo 的信息的代码(它有效)。使用%*s 我可以跳过为每一行存储特定列。因此,跳过 5 次后,我可以存储 vendor_id。但是为什么之后要跳过4次才能拿到cpu族呢?

{
    int fd = open("/proc/cpuinfo", O_RDONLY);
    char *buffer = (char *)malloc(BUFF_SIZE);
    int length = read(fd, buffer, BUFF_SIZE);
    
    sscanf(buffer, "%*s %*s %*s %*s %*s %s %*s %*s %*s %s %*s %*s %s",
           vendor_id, cpu_family, cpu_model);
}

【问题讨论】:

  • 你不是跳过 4 次,而是跳过 3 次。一种用于cpu,一种用于family,一种用于:
  • 您可能会发现 libcpuid 很有趣,它可以作为解析 /proc/cpuinfo 的替代方法(也适用于其他操作系统)。

标签: c character scanf


【解决方案1】:

您可以通过一个 sscanf() 调用来实现您的目标,但它更复杂:

  • 您必须以空值终止缓冲区,因为read 不会添加空值终止符;
  • 您必须跳过整行,而不仅仅是单词;
  • 您必须跳过图例(或者您可能会匹配它);
  • 您应该保护目标数组以避免未定义的行为
  • 您应该测试是否正确解析。
// get CPU info into 3 char arrays of at least 100 bytes.
// returns -1 on error, 0 
int get_info(char vendor_id[100], char cpu_family[100], char cpu_model[100]) {
    char buffer[BUFF_SIZE];
    int fd = open("/proc/cpuinfo", O_RDONLY);
    int length;

    if (fd < 0)
        return -1;

    length = read(fd, buffer, BUFF_SIZE - 1);
    close(fd);
    if (length <= 0)
        return -1;

    buffer[length] = '\0';    
    if (sscanf(buffer, "%*[^\n] "           // skip the processor line
                       "%*[^:]: %99[^\n] "  // skip the legend and parse vendor_id
                       "%*[^:]: %99[^\n] "  // skip the legend and parse cpu family
                       "%*[^:]: %99[^\n]",  // skip the legend and parse model
                       vendor_id, cpu_family, cpu_model) != 3) {
        return -1;
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 2011-01-01
    • 2022-01-05
    • 2011-10-30
    • 1970-01-01
    • 1970-01-01
    • 2019-01-18
    • 2017-09-22
    • 2010-12-30
    • 1970-01-01
    相关资源
    最近更新 更多