PDA

View Full Version : C: trovare riga in un file che inizia in un certo modo


ruggeroerre
19-10-2015, 22:55
Salve a tutti,:)
ho un file di testo ad esempio:

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

devo scrivere un programma in C che analizza il File e trova la riga i cui primi x caratteri sono "model name" (ad esempio). successivamente devo estrarre da questa riga il valore associato allo specifico campo (Pentium II (Deschutes) ). Questo è il codice che ho scritto:

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);
}

Il problema è che il buffer risulta sempre troppo piccolo......

sottovento
20-10-2015, 07:33
Il buffer non e' piccolo. Dovresti mettere qualche controllo, per esempio
- in apertura del file

fp = fopen("/proc/cpuinfo", "r");
if (fp == NULL)
{
perror ("Error opening /proc/cpuinfo");
return 0;
}

- sulla stringa di ingresso (come fai ad esser sicuro di non sfondare la lunghezza massima? Io passerei un secondo parametro contenente la lunghezza massima);
- controllerei anche questa condizione:

if (bytes_read == 0 || bytes_read == sizeof (buffer))
return 0;

Ritorni 0 se non leggi nulla o se il buffer e' pieno. Pero' nel secondo caso potresti anche tentare una lettura dell'informazione che ti interessa. Ad ogni modo, non sarebbe meglio distinguere le due situazioni? D'altronde ne hai bisogno per capire come agire per correggerla, no?