我必须在文本文件中找到以关键字开头的特定行,然后我必须分析这一行以提取信息。我会通过一个例子来说明:
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);
}
它说缓冲区总是不够大......