I am relatively new to C language and Linux systems I would like some feedback/review. The main function of the code is to read the dhcpcd file looking for the 3 lines and then either adding/removing to the new file. It works and the Pi can switch from AP to client without a reboot, but I feel like it is more of a hack than a proper solution.
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct word {
int linenumber;
char *value;
};
struct words {
int wordcount;
struct word wordlist[3];
};
int main(void) {
FILE *fp;
FILE *temp;
char filename[] = "/etc/dhcpcd.conf";
char tempname[] = "/etc/temp.conf";
char *line = NULL;
size_t len = 0;
ssize_t read;
int linecount = 0;
int index = 0;
int shouldSkip = 0;
struct words searchlist;
struct word wordA;
struct word wordB;
struct word wordC;
wordA.value = "interface wlan0";
wordA.linenumber = -1;
wordB.value = "static ip_address=192.168.4.1/24";
wordA.linenumber = -1;
wordC.value = "nohook wpa_supplicant";
wordC.linenumber = -1;
searchlist.wordcount = 3;
searchlist.wordlist[0] = wordA;
searchlist.wordlist[1] = wordB;
searchlist.wordlist[2] = wordC;
fp = fopen(filename, "r");
temp = fopen(tempname, "w");
if (fp == NULL || temp == NULL) {
printf("Unable to open file!\n");
exit(-1);
}
while ((read = getline(&line, &len, fp)) != -1) {
struct word *xword = &searchlist.wordlist[index];
if(strstr(line, xword->value) != NULL) {
xword->linenumber = linecount;
if(index > 0 && index != searchlist.wordcount - 1) {
if ((linecount - searchlist.wordlist[index - 1].linenumber) != 1) {
for (int i = 0; i < searchlist.wordcount; i++) {
struct word *wd = &searchlist.wordlist[i];
wd->linenumber = -1;
index = 0;
}
}
}
index = (index == (searchlist.wordcount - 1)) ? index : index + 1;
}
linecount++;
}
linecount = 0;
//AP is on so toggle off
if (fseek(fp, 0L, SEEK_SET) == 0) {
while ((read = getline(&line, &len, fp)) != -1) {
for(int i = 0; i < searchlist.wordcount; i++) {
if(linecount == searchlist.wordlist[i].linenumber && strstr(line, searchlist.wordlist[i].value) != NULL) {
shouldSkip = 1;
}
}
if(!shouldSkip)
fputs(line, temp);
shouldSkip = 0;
linecount++;
}
}
if (index != searchlist.wordcount - 1) {
for(int i = 0; i < searchlist.wordcount; i++) {
fputs(searchlist.wordlist[i].value, temp);
fputs("\n", temp);
}
}
fclose(fp);
fclose(temp);
remove(filename);
rename(tempname, filename);
if(line)
free(line);
if (index == searchlist.wordcount - 1) {
printf("Turning WIFI on\n");
} else {
printf("Turning Access Point on\n");
}
system("sudo service hostapd stop");
system("sudo service dhcpcd restart");
system("sudo service hostapd start");
exit(0);
}