How to Write a function to read entire file into memory:
Whenever we need to read file by the time we need to know the exact file size or else we keep on reading file with maximum size. suppose if the file size is 20 bytes but you are allocating the memory as 1024 bytes then huge amount of the bytes has been wasted here. Also if you are allocating memory for 1024 bytes at the same time the file size exceeds 1024 bytes application will crash at any point of time. Here is the program to over come this issue.
#include<sys/stat.h> #include<stdio.h> #include<string.h> #include<stdlib.h> char *ReadFile(const char *fileName) { FILE *fh =NULL; char *text =NULL; struct stat prop; /* error cases not handled */ stat(fileName, &prop); fh =fopen(fileName, "r"); text = (char*)malloc(prop.st_size * sizeof(char)); fread(text,sizeof(char), prop.st_size, fh); fclose(fh); return text; } int main(int argc,char *argv[]) { if(argc == 2) { printf("File is : %s\n",ReadFile(argv[1])); } else printf("Pleasee enter the filename\n"); }
compile : gcc filereading.c -o output.exe
Output 1 with wrong input:
===========================
./output.exe
Please enter the filename
Output 2 with proper input:
==========
Create one new file or else you can choose existing file to test the above program output.Here i am going to create one new file in the name of response.txt.
I am adding the following string in the string.
Hello World!!!
This entire file data will be read by output.exe file.
./output.exe response.txt
File is : Hello World!!!
This entire file data will be read by output.exe file.
Program explanation:
This program input needs to given in the command line argument. We just check whether theagrc value it is 2 or not. If the value is 2 then we consider second argument as file name of the file which needs to read.
prop is the stat structure type. Which is used to fetch the file details. In this prop structure object address we need to pass as the argument of the stat() function along with the filename. The stat function will fetch the given file details. It will return 0 if the file details properly read otherwise it will return -1 and also the error will be set into errno. Then we open the file with fopen. Allocating the memory based on the file size. The prop.st_size will return the size of the file. So we need to allocate the memory for the file size. Then we read the given file and store it into the text. Finally we return text value. The memory has been allocated by heap so we need to free the memory whatever allocated.
You can do error handling by yourself. Say for example if your input filename doesn’t have read permission or file not found by the time the above code will crash. So you need to check the return value in man page and do the error handling.