Browse Source

rework as function

master
Screenager 6 years ago
parent
commit
87dd764acc
  1. 15
      main.c
  2. 7
      makefile
  3. 53
      read_cfg.c
  4. 12
      read_cfg.h
  5. 22
      test.c
  6. 9
      test.cfg

15
main.c

@ -0,0 +1,15 @@
#include<stdio.h>
#include<stdlib.h>
#include"read_cfg.h"
int main(){
char file[]="test.cfg";
options *option;
option=read_cfg(file); //returns pointer to struct with options
printf(option[1].name);printf("\n");
printf(option[1].setting);printf("\n");
printf(option[2].name);printf("\n");
printf(option[2].setting);printf("\n");
free(option); //freeing memory that got alloced in the function read_cfg
return 0;
}

7
makefile

@ -0,0 +1,7 @@
CC=gcc
CFLAGS=-O2
LIBS=
all: main.c read_cfg.c read_cfg.h
$(CC) -o test.exe main.c read_cfg.c $(CFLAGS) $(LIBS)

53
read_cfg.c

@ -0,0 +1,53 @@
/*reads a config file with the following format:
name1=setting1
name2=setting2
example:
relay = FALSE
debug = 1
mods=12345;98765;13456
returns a pointer to a struct wich needs to be freed later on
should be portable on pretty much every platform where there is a C compiler with malloc() and enough RAM, this is not optimized for ICs
constants and struct defined in header
implement comments later
*/
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"read_cfg.h"
options *read_cfg(char filename[]) {
FILE *fpointer;
char str[LINEBUFF];
char line[LINEBUFF];
int i=0;
int ib=0;
int il=0;
options *option;
option = malloc(MAXLINE*sizeof(*option)); //160 KB HEAP needs to be freed later in main.c
if ((fpointer = fopen(filename,"r")) == NULL){
printf("Error opening file");
return 0;
}
while( fgets (str, LINEBUFF, fpointer)!=NULL || il<=MAXLINE ) {
while (i<LINEBUFF){
if(str[i]!=' ' && str[i]!='\n' && str[i]!='\r'){line[ib]=str[i];i++;ib++;}
else{i++;}
}
if (line[0]!='\0'){
i=0;ib=0;
strcpy(option[il].name,strtok(line, "="));
strcpy(option[il].setting,strtok(NULL, "="));
}
else{}
il++;
}
fclose(fpointer);
return option;
}

12
read_cfg.h

@ -0,0 +1,12 @@
//no dynamic growth use these to set your limits
#define LINEBUFF 4096 //how many bytes per fgets()
#define MAXLINE 20 //how many lines you want to parse max
//struct with options
typedef struct options{
char name[LINEBUFF];
char setting[LINEBUFF];
}options;
options *read_cfg(char filename[]);

22
test.c

@ -1,22 +0,0 @@
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main() {
FILE *fpointer;
char str[60];
char strb[60];
int i=0;
int ib=0;
if ((fpointer = fopen("test.cfg","r")) == NULL){
printf("Error opening file");
exit(1);
}
while( fgets (str, 60, fpointer)!=NULL ) {
while (i<60){
if(str[i]!=' '){strb[ib]=str[i];i++;ib++;}else{i++;}
}
puts(strb);i=0;ib=0;
}
fclose(fpointer);
return 0;
}

9
test.cfg

@ -1,2 +1,7 @@
line1 line1 = alasdads
line2 line2=lel
mods = asdasd;94343;deinemudder //testst
line4 = lerare
Loading…
Cancel
Save