我必须在文本文件中找到以关键字开头的特定行,然后我必须分析该行以提取信息。我将通过一个例子来清楚地说明:
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 5
model name : Pentium II (Deschutes)
stepping : 2
cpu MHz : 400.913520
cache size : 512 KB
fdiv_bug : no
hlt_bug : no
这是文本文件(Linux 中的/proc/cpuinfo)。我必须编写一个函数来解析文件,直到找到“型号名称:”,然后它必须将信息“Pentium II (Deschutes)”存储在字符数组中。 这是我到目前为止编写的代码:
int get_cpu(char* info)
{
FILE *fp;
char buffer[1024];
size_t bytes_read;
char *match;
/* Read the entire contents of /proc/cpuinfo into the buffer. */
fp = fopen("/proc/cpuinfo", "r");
bytes_read = fread(buffer, 1, sizeof (buffer), fp);
fclose (fp);
/* Bail if read failed or if buffer isn't big enough. */
if (bytes_read == 0 || bytes_read == sizeof (buffer))
return 0;
/* NUL-terminate the text. */
buffer[bytes_read] == '\0';
/* Locate the line that starts with "model name". */
match = strstr(buffer, "model name");
if (match == NULL)
return 0;
/* copy the line */
strcpy(info, match);
}
它说缓冲区总是不够大......
最佳答案
这不仅仅是 /proc/cpuinfo
通常大于 1024 字节这一简单事实:
> wc -c </proc/cpuinfo
3756
这样,当然你的缓冲区太小,无法一次读取整个文件......
您在这里尝试的是处理一个文本文件,而自然的处理方式是逐行。
尝试类似的事情
(编辑:最终用经过测试的代码替换整个内容...要使 strtok()
正确并不是那么容易...呵呵)
#include <stdio.h>
#include <string.h>
int main(void)
{
char buf[1024];
char *val = 0;
FILE *fp = fopen("/proc/cpuinfo", "r");
if (!fp)
{
perror("opening `/proc/cpuinfo'");
return 1;
}
while (fgets(buf, 1024, fp)) /* reads one line */
{
char *key = strtok(buf, " "); /* gets first word separated by space */
if (!strcmp(key, "model"))
{
key = strtok(0, " \t"); /* gets second word, separated by
* space or tab */
if (!strcmp(key, "name"))
{
strtok(0, " \t"); /* read over the colon */
val = strtok(0, "\r\n"); /* read until end of line */
break;
}
}
}
fclose(fp);
if (val)
{
puts(val);
}
else
{
fputs("CPU model not found.\n", stderr);
}
return 0;
}
用法:
> gcc -std=c89 -Wall -Wextra -pedantic -o cpumodel cpumodel.c
> ./cpumodel
AMD A6-3670 APU with Radeon(tm) HD Graphics
关于c - 查找文件中的一行并提取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33224472/