diff --git a/file.c b/file.c new file mode 100644 index 0000000..b5e971c --- /dev/null +++ b/file.c @@ -0,0 +1,53 @@ +#include "file.h" +#include +/* + * Here we load a file and write the file as string to a memory address: + * Input: + * char* fname: the name of the file to open + * int cbSize: the size of the strContent + * Output: + * char **strContent: a pointer to a address where you have to allocate enougth memory to store the whole file + * int neededSize: this returns the needed size of the buffer strContent + * + * Note: + * to get the size define strContent as NULL, then the needed size will return the needed buffersize + * + * + */ +int getFile(char *fname, char **strContent,int cbSize,long *neededSize) +{ + FILE *hfile = fopen(fname,"r"); + long file_size=0; + int ret=0; + if(hfile == NULL) + { + return FILE_ERROR_OPEN; + } + fseek(hfile,0,SEEK_END); + file_size = ftell(hfile); + if(strContent == NULL) //we must determine the size and return to neededSize + { + *neededSize = file_size; + fclose(hfile); + return NO_ERROR; + } + + if(cbSize < file_size) + { + *neededSize = file_size; + fclose(hfile); + return FILE_ERROR_STRCONTENT_TO_SMALL; + } + + fseek(hfile,0,SEEK_SET); + ret=fread(*strContent,file_size,1,hfile); + if(ret != 1) + { + printf("Reading error read and should read missmatch\nnumber written elements:%d\n", + ret); + fclose(hfile); + return FILE_ERROR_READ_MISMATCH; + } + fclose(hfile); + return NO_ERROR; +} diff --git a/file.h b/file.h new file mode 100644 index 0000000..34328c5 --- /dev/null +++ b/file.h @@ -0,0 +1,8 @@ +#define NO_ERROR 0 + +//ERRORS +#define FILE_ERROR_OPEN 11 +#define FILE_ERROR_STRCONTENT_TO_SMALL 12 +#define FILE_ERROR_READ_MISMATCH 13 + +int getFile(char *fname, char **strContent,int cbSize,long *neededSize); diff --git a/test.c b/test.c index 96f1851..da1a353 100644 --- a/test.c +++ b/test.c @@ -1,6 +1,7 @@ #include "config.h" #include #include +#include "file.h" int main(void) { @@ -24,6 +25,7 @@ int main(void) char testpair[] = "asifdsfo=s1254124"; char *keyName=NULL; char *keyValue=NULL; + char *content=NULL; keyName = malloc(MAX_LEN_SECTIONNAME); keyValue = malloc(MAX_LEN_SECTIONNAME); @@ -37,6 +39,26 @@ int main(void) }else{ printf("error getNameValuePair: %d\n",ret); } + + long neededSize=0; + if((ret=getFile("config.cfg",NULL,0,&neededSize))==NO_ERROR) + { + printf("sucessfull retrieved size:%ld\n",neededSize); + } + else { + printf("Error on getFile:%d\n",ret); + } + content = malloc(neededSize); + if((ret=getFile("config.cfg",&content,neededSize,&neededSize))==NO_ERROR) + { + printf("Sucessfull read file into buffer:%s\n---\n",content); + } + else { + printf("Error on getFile:%d\n",ret); + } + + + free(keyValue); free(keyName); @@ -44,3 +66,4 @@ int main(void) } +