【发布时间】:2015-10-19 21:45:58
【问题描述】:
我必须在文本文件中找到以关键字开头的特定行,然后我必须分析该行以提取信息。我举个例子说清楚:
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);
}
说缓冲区总是不够大......
【问题讨论】:
-
“它说缓冲区总是不够大”。那是因为它不够大。只需手动运行
cat /proc/cpuinfo > output并查看output文件的大小。你发现了什么? -
在我的系统上这是一个非常大的文档...我应该编写一个可以在每个 Linux 系统上运行的程序
-
@kaylum useless use of cat 检测到 *scnr*(仍然 +1)[解释:如果你想用
ls进行检查,一个简单的cp就可以了 - - 最好使用wc -c]