57 lines
1.5 KiB
C
57 lines
1.5 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;
|
|
}
|
|
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;
|
|
}
|
|
strContent[*neededSize]='\0';
|
|
fclose(hfile);
|
|
return NO_ERROR;
|
|
}
|
|
|
|
|