-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.c
67 lines (56 loc) · 1.48 KB
/
file.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include "file.h"
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
/*
* Takes an input file, expects /proc/cpuinfo with field names and values separated by semicolons
* Returns pointer to field contents, NULL if field could not be found
*/
char *procParse(FILE *cpuinfo, char *buffer, char *field) {
char *cpuEntry = NULL;
size_t size = 0;
while(getline(&cpuEntry, &size, cpuinfo) != -1) {
if (strstr(cpuEntry, field) != NULL) {
// Clean this up
char *entryText = strstr(cpuEntry, ":") + 1;
while ( *entryText == ' ') {
entryText++;
}
// Replace newline character with null terminator
*strstr(entryText, "\n") = '\0';
// Allocate exact memory for final string
strcpy(buffer, entryText);
// Free line pointer
free(cpuEntry);
return buffer;
}
}
// Return NULL if desired entry was not found
return NULL;
}
char *osParse(FILE *os_release, char *buffer, char *field) {
char *osEntry = NULL;
size_t size = 0;
while(getline(&osEntry, &size, os_release) != -1) {
if (strstr(osEntry, field) != NULL) {
char *entryText = strstr(osEntry, "=") + 1;
*strstr(entryText, "\n") = '\0';
while ( *entryText == ' ' || *entryText == '\"') {
entryText++;
}
*strstr(entryText, "\"") = '\0';
strcpy(buffer, entryText);
free(osEntry);
return buffer;
}
}
buffer[0] = '\0';
return NULL;
}
char *readFirstline(FILE *f) {
char *line = NULL;
size_t size = 0;
getline(&line, &size, f);
*strstr(line, "\n") = '\0';
return line;
}