I want to read the content of a .txt file and store it in a buffer.
To read the file I use fread()
.
The manpage says:
" On success, fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when size is 1."
The problem I encounter is, that in the following code the function call returned 216 bytes. But in the final buffer the content consists of only a single char.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
bool readFile(const char* pFileName, char* outFile) {
FILE* myFile;
myFile = fopen(pFileName, "r");
if (myFile == NULL) {
printf("File could not be opened.");
return false;
}
printf("Size of my file: %d\n",sizeof(*myFile));
printf("Size of output buffer %d\n",sizeof(outFile));
printf("sizeof(*outFile) / sizeof(outFile) %d\n",sizeof(*myFile) / sizeof(myFile[0]));
size_t res = fread(outFile, sizeof(*outFile), sizeof(*outFile)/sizeof((outFile)[0]), myFile);
printf("freadResult: %d\n", res*sizeof(*myFile));
fclose(myFile);
return true;
}
int main(){
char* fileName = "test.txt";
char* outFile = (char*)malloc(4096);
bool result = readFile(fileName, outFile);
if(!result){
printf("Error\n");
} else {
printf("Success\n");
for(char* tmp = outFile; *tmp != '\0' ; tmp){
printf("%c", *tmp);
}
printf("\n");
}
printf("Programm finished\n");
return 0;
}
The test.txt file has the following three lines as content:
I was
opened
successfully!
If I build and execute the readFileTest I get the following output:
$ gcc readFileTest.c -o readFileTest
$ ./readFileTest
>Size of my File: 216
>Size of output Buffer 8
>sizeof(*outFile) / sizeof(outFile) 1
>freadResult: 216
>Success
>I
>Programm finished
CodePudding user response:
In this line
size_t res = fread(outFile, sizeof(*outFile), sizeof(*outFile)/sizeof((outFile)[0]), myFile);
the expression sizeof(*outFile)
is equivalent to the expression sizeof(char)
(the type of the variable outFile
is char *
so the type of the expression *outFile
that is the same as outFile[0]
is char
) and equal to 1
. At the same time the expression sizeof(*outFile)/sizeof((outFile)[0])
is equivalent to sizeof(char)/sizeof(char )
and a;so is equal to 1
.
You need to pass to the function the actual size of the dynamically allocated array and use it within the function.
Pay attention to that to output values of sizeof
operator you have to use the conversion specifier zu
instead of d
in calls of printf and in this call
printf("Size of my file: %d\n",sizeof(*myFile));
the expression sizeof(*myFile)
yields the size of the structure FILE
. It is not the size of the file.