Today i was trying to write a program and i realized that i need one file to be read in more places inside my program, but before i got there i had the following:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *printFile(char *fileName){
long int length;
char *buffer;
size_t size;
FILE *file;
file = fopen (fileName , "r" );
fseek (file , 0 , SEEK_END);
length = ftell (file);
fseek (file , 0 , SEEK_SET);
buffer = (char *) malloc (sizeof(char)*(size_t)length);
if (buffer == NULL){
fputs ("Memory error",stderr);
exit (2);
}
size = fread (buffer,1,(size_t) length,file);
if (size != (size_t)length){
fputs ("Reading error",stderr);
exit(3);
}
fclose (file);
return buffer;
}
int main (void) {
char *fileName = "test.txt";
char *fileContent = printFile(fileName);
printf("%s", fileContent);
free(fileContent);
return 0;
}
As you can see i have used free in the main function, and after i realized that that's not ok for my program I decided to free that buffer inside the printFile function, and I now have this:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *printFile(char *fileName){
long int length;
char *buffer,*buffer2;
size_t size;
FILE *file;
file = fopen (fileName , "r" );
if (file == NULL){
fputs ("File error",stderr);
fclose (file);
exit (1);
}
fseek (file , 0 , SEEK_END);
length = ftell (file);
fseek (file , 0 , SEEK_SET);
buffer = (char *) malloc (sizeof(char)*(size_t)length);
if (buffer == NULL){
fputs ("Memory error",stderr);
exit (2);
}
buffer2 = (char *) malloc (sizeof(char)*(size_t)length);
if (buffer2 == NULL){
fputs ("Memory error",stderr);
exit (2);
}
size = fread (buffer,1,(size_t) length,file);
if (size != (size_t)length){
fputs ("Reading error",stderr);
exit(3);
}
strcpy (buffer2, buffer);
fclose (file);
free(buffer);
return buffer2;
}
int main (void) {
char *fileName = "test.txt";
char *fileContent = printFile(fileName);
printf("%s", fileContent);
return 0;
}
As you probably noticed i used a second pointer (*buffer2) to copy the content of the first buffer inside of it before I free it the first one.
My question is: is my approach right or wrong?