config-parser
a simple ini parser written in C
 
Loading...
Searching...
No Matches
file.c
Go to the documentation of this file.
1#include "file.h"
2#include <stdio.h>
3/*
4 * Here we load a file and write the file as string to a memory address:
5 * Input:
6 * char* fname: the name of the file to open
7 * int cbSize: the size of the strContent
8 * Output:
9 * char **strContent: a pointer to a address where you have to allocate enougth memory to store the whole file
10 * int neededSize: this returns the needed size of the buffer strContent
11 *
12 * Note:
13 * to get the size define strContent as NULL, then the needed size will return the needed buffersize
14 *
15 *
16 */
17int getFile(char *fname, char **strContent,int cbSize,long *neededSize)
18{
19 FILE *hfile = fopen(fname,"r");
20 long file_size=0;
21 int ret=0;
22 if(hfile == NULL)
23 {
24 return FILE_ERROR_OPEN;
25 }
26
27 printf("file openend:%s",fname);
28 fseek(hfile,0,SEEK_END);
29 file_size = ftell(hfile);
30 if(strContent == NULL) //we must determine the size and return to neededSize
31 {
32 *neededSize = file_size+1;
33 fclose(hfile);
34 return NO_ERROR;
35 }
36
37 if(cbSize < file_size)
38 {
39 *neededSize = file_size+1; //null terminator
40 fclose(hfile);
42 }
43
44 fseek(hfile,0,SEEK_SET);
45 ret=fread(*strContent,file_size,1,hfile);
46 if(ret != 1)
47 {
48 printf("Reading error read and should read missmatch\nnumber written elements:%d\n",
49 ret);
50 fclose(hfile);
52 }
53 //buffer end-1 = \0
54 //buffer end-2 = \n
55 //buffer end-3 = last character
56 printf("strcontent: %ld, [%c]\n",*neededSize,*(*strContent+ *neededSize-3));
57 *(*strContent + *neededSize -1) ='\0';
58 printf("after zero assign: %ld, %s\n",*neededSize,(*strContent+ *neededSize-1));
59 //printf("content:%s",*strContent);
60 fclose(hfile);
61 return NO_ERROR;
62}
63
64
#define NO_ERROR
Definition config.h:5
int getFile(char *fname, char **strContent, int cbSize, long *neededSize)
Definition file.c:17
#define FILE_ERROR_STRCONTENT_TO_SMALL
Definition file.h:5
#define FILE_ERROR_OPEN
Definition file.h:4
#define FILE_ERROR_READ_MISMATCH
Definition file.h:6