Hi All,
this is my first C code in my professional life. I wanted to write a common function to retrieve file content. I do not know whether below code is upto the mark or not.
any Suggestions/modifications/tips are greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
/*
Function Name: get_file_content
Description: fills content of the file to given buffer.
Parameters: file to be read(in), Mode(in), destination buffer(out)
Return Type: pointer to content (SUCCESS), otherwise NULL
*/
char* get_file_content (char *file_name, char *file_mode, char *file_content)
{
FILE *fp;
long file_size;
size_t bytes_read;
//open file
if (!(fp = fopen (file_name, file_mode))) {
printf ("*** Unable to open file ***\n");
return NULL;
}
//get file size
fseek (fp, 0, SEEK_END);
file_size = ftell (fp);
rewind (fp);
printf("*** size = %ld ***\n", file_size);
//check memory
file_content = (char *) realloc (file_content, sizeof(char) * file_size);
if (file_content == NULL) {
printf("*** memory insufficient ***");
fclose (fp);
return NULL;
}
//get content
bytes_read = fread (file_content, sizeof(char), file_size, fp);
if (bytes_read != file_size) {
printf("*** read failed ***");
fclose (fp);
return NULL;
}
//put EOS
file_content[bytes_read-1] = '\0';
//clean
fclose (fp);
//success
return file_content;
}
int main (int argC, char *argV[])
{
int status = -1;
char *file_content = (char *) malloc (2);
if ((file_content = get_file_content ("metadata.txt", "r", file_content)) == NULL){
status = 1;
goto FREE_BLOCK;
}
printf("\n#%s#\n", file_content);
FREE_BLOCK:
free (file_content);
return 0;
}
Regards,
Vashek