Skip to content

Instantly share code, notes, and snippets.

@GuilhermeRossato
Created April 23, 2019 22:39
Show Gist options
  • Save GuilhermeRossato/6d3fa3e921213967321ecb7290060bf1 to your computer and use it in GitHub Desktop.
Save GuilhermeRossato/6d3fa3e921213967321ecb7290060bf1 to your computer and use it in GitHub Desktop.
A script to run other programs defined in a configuration file
//
//
// Works both on windows and linux
//
//
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#define FILE_CONFIG_NAME "program-config.txt"
int file_exists(const char* filename){
struct stat buffer;
int exist = stat(filename,&buffer);
if(exist == 0)
return 1;
else // -1
return 0;
}
char file_content_buffer[1024];
char * file_get_contents(const char * filename) {
FILE *fp;
fp = fopen(filename, "r");
int length = fread(file_content_buffer, 1, 1024, fp);
printf("read %d\n", length);
fclose(fp);
return file_content_buffer;
}
#define FILE_CREATE 0
#define FILE_APPEND 1
int file_put_contents(const char * filename, char * buffer, int mode) {
FILE *fp;
if (mode == FILE_APPEND) {
fp = fopen(filename, "a");
} else {
fp = fopen(filename, "w");
}
int bytes = fputs(buffer, fp);
fclose(fp);
return bytes;
}
int for_each_line(char * buffer, void (*callback)(char *)) {
int i;
int buffer_index = 0;
char buffer_line[1024];
for (i=0;i<1024;i++) {
//printf("byte %d = %d [%c]\n", i, buffer[i], buffer[i]);
if (buffer[i] == '\n' || buffer[i] == '\r' || buffer[i] == '\0') {
buffer_line[buffer_index++] = '\0';
if (buffer_line[0] != '\0' && buffer_index >= 2) {
callback(buffer_line);
}
buffer_index = 0;
buffer_line[0] = '\0';
if (buffer[i] == '\0') {
break;
}
} else {
buffer_line[buffer_index++] = buffer[i];
}
}
}
char sysbuffer[256];
void process_config_line(char * line) {
int is_windows = 0;
#ifdef _WIN32
is_windows = 1;
#endif
if (file_exists(line)) {
if (is_windows) {
snprintf(sysbuffer, 256, "start %s", line);
} else {
snprintf(sysbuffer, 256, "xdg-open %s", line);
}
printf("Executing the command \"%s\"\n", sysbuffer);
system(sysbuffer);
} else {
printf("File not found: %s\n", line);
}
}
int main(int argn, char ** argc) {
if (!file_exists(FILE_CONFIG_NAME)) {
printf("Config file not found: " FILE_CONFIG_NAME "\n");
return 0;
}
char * data = file_get_contents(FILE_CONFIG_NAME);
for_each_line(data, process_config_line);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment