I am programing in C language and have created the below functions to read files. There are two functions that I can use to read files. I wanted to know how I can further improve these two in terms of efficiency and out of these two which one would be better to use for reading files.
First is:
char *read_data_from_file(char *data, char *path, int *fsz1)
{
int imgFD=0;
struct stat fst;
int fsz = *fsz1;
fsz = 0;
imgFD = open(path, O_RDONLY);
if (imgFD <= 0){
*fsz1 = fsz;
return NULL;
}
fstat(imgFD, &fst);
fsz = fst.st_size;
printf("the size %s = %d inmfd = %d \n ", path, fsz, imgFD);
if (fsz <= 0){
*fsz1 = fsz;
return NULL;
}
data = (char *)malloc(sizeof(char)*(fsz+1));
read(imgFD, data, fsz);
close(imgFD);
*fsz1 = fsz;
return (data);
}
Another is:
int read_data_from_file(int fd, void *buffer, int count)
{
void *pts = buffer;
int status = 0, n;
if(count < 0) return -1;
while(status != count) {
n = read(fd, pts+status, count-status);
if(n < 1) return n;
status += n;
}
return (status);
}
The calling portion of the above mentioned function is:
int main(int argc, char *argv[])
{
struct stat sb;
off_t len;
char *p, *buffer = NULL;
int fd;
fd = open("test.txt" , O_RDONLY);
if (fd == -1) {
perror ("open");
return 1;
}
if (fstat (fd, &sb) == -1) {
perror ("fstat");
return 1;
}
if (!S_ISREG (sb.st_mode)) {
fprintf (stderr, "%s is not a file\n", argv[1]);
return 1;
}
debug_print("printing start time and size : %d\n", sb.st_size);
buffer = (char *)malloc(sizeof(char) * (sb.st_size + 1));
read_data_from_file(fd, buffer, sb.st_size);