Поскольку вы используете r без инициализации при вводе в l oop с неопределенным поведением, трудно найти вашу проблему, не зная определения ReadTextLine .
Другой ответ говорит о некоторых возможных проблемах.
Вот предложение сделать работу:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char * get_cpu()
{
FILE * fp = fopen("/proc/cpuinfo", "r");
char line[256];
char * result = NULL;
if (fp == NULL) {
/* low probability to happen */
perror("cannot read /proc/cpuinfo");
return NULL;
}
while (fgets(line, sizeof(line), fp) != NULL) {
char * match = strstr(line, "model name");
/* bypass ':' then possible spaces */
if ((match != NULL) && ((match = strchr(match, ':')) != NULL)) {
do
match += 1;
while (*match && isspace((unsigned char) *match));
if (*match) {
/* remove possible spaces including \r\n at end of line */
char * pend = match + strlen(match);
while (isspace((unsigned char) *--pend))
*pend = 0;
/* duplicate the string to not return an address in the stack */
result = strdup(match);
break;
}
}
}
fclose(fp);
return result;
}
int main()
{
char * s = get_cpu();
if (s != NULL) {
printf("(first) cpu is '%s'\n", s);
/* the result was allocated, free it when not needed anymore */
free(s);
}
return 0;
}
Компиляция и выполнение:
pi@raspberrypi:/tmp $ gcc -Wall -Werror -pedantic c.c
pi@raspberrypi:/tmp $ ./a.out
(first) cpu is 'ARMv7 Processor rev 3 (v7l)'
pi@raspberrypi:/tmp $
В моем случае начало / proc / cpuinfos начинается с:
pi@raspberrypi:/tmp $ head -2 /proc/cpuinfo
processor : 0
model name : ARMv7 Processor rev 3 (v7l)
pi@raspberrypi:/tmp $
Если вы действительно хотите иметь функцию ReadTextLine , она должна делать больше, чем просто fgets , поэтому давайте решим, что он также удаляет пробелы в конце строки (в этом контексте бесполезно перемещать пробелы в начале строки)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
char * ReadTextLine(FILE * fp, char * line, int size)
{
if (fgets(line, size, fp) == NULL)
return NULL;
/* remove possible spaces including \r\n at end of line */
char * pend = line + strlen(line);
while ((pend != line) && isspace((unsigned char) *--pend))
*pend = 0;
return line;
}
char * get_cpu()
{
FILE * fp = fopen("/proc/cpuinfo", "r");
char line[256];
char * result = NULL;
if (fp == NULL) {
/* probably never happend under linux */
perror("cannot read /proc/cpuinfo");
return NULL;
}
while (ReadTextLine(fp, line, sizeof(line)) != NULL) {
char * match = strstr(line, "model name");
/* bypass ':' then possible spaces */
if ((match != NULL) && ((match = strchr(match, ':')) != NULL)) {
do
match += 1;
while (*match && isspace((unsigned char) *match));
if (*match) {
result = strdup(match);
break;
}
}
}
fclose(fp);
return result;
}