Files
config-parser/file.c

65 lines
1.8 KiB
C

#include "file.h"
#include <stdio.h>
/*
* 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;
}
printf("file openend:%s",fname);
fseek(hfile,0,SEEK_END);
file_size = ftell(hfile);
if(strContent == NULL) //we must determine the size and return to neededSize
{
*neededSize = file_size+1;
fclose(hfile);
return NO_ERROR;
}
if(cbSize < file_size)
{
*neededSize = file_size+1; //null terminator
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;
}
//buffer end-1 = \0
//buffer end-2 = \n
//buffer end-3 = last character
printf("strcontent: %ld, [%c]\n",*neededSize,*(*strContent+ *neededSize-3));
*(*strContent + *neededSize -1) ='\0';
printf("after zero assign: %ld, %s\n",*neededSize,(*strContent+ *neededSize-1));
//printf("content:%s",*strContent);
fclose(hfile);
return NO_ERROR;
}