add file operation

This commit is contained in:
jonathan santis
2025-05-13 13:49:10 +02:00
parent 3afd472bbd
commit 631fc8322a
3 changed files with 84 additions and 0 deletions

53
file.c Normal file
View File

@@ -0,0 +1,53 @@
#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;
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;
}