I am trying to create a function that reads everything from a file and puts it into memory.
void fileRead(char *filePtr,const char *filename)
Successfully copies the data from the file into the char *buffer variable,
the char *filePtr then points to what char *buffer is pointing to.
For some reason I just cannot seem to access the file data after the function ends.
char *copydatatohere;
fileRead(copydatatohere,"myfile.txt");
printf("%s",copydatatohere); <------------copydatatohere points to nothing.????! why?
Code:
#include <stdio.h>
#include <stdlib.h>
void displayUsage(){
printf("-----------------------------\n");
printf("Usuage: bwPercentage input.bmp\n");
printf("-----------------------------\n");
}
void fileRead(char *filePtr,const char *filename){
FILE * pFile;
long lSize;
size_t result;
char *buffer;
pFile = fopen ( filename, "rb" );
if (pFile==NULL) {
fputs ("File error",stderr);
exit (1);
}
fseek (pFile , 0 , SEEK_END);
lSize = ftell (pFile);
rewind (pFile);
buffer = (char*) malloc (sizeof(char)*lSize);
if (buffer == NULL) {
fputs ("Memory error",stderr);
exit (2);
}
result = fread (buffer,1,lSize,pFile);
if (result != lSize) {
fputs ("Reading error",stderr);
exit (3);
}
fclose (pFile);
filePtr = buffer;
//printf("%s",filePtr); WORKS?!
//why doesn't the char *data variable point to the buffer after this function finishes?
}
int main(int argc, char **argv)
{
char *filename;
if(argc == 2){
filename = argv[1];
}
else{
displayUsage();
exit(EXIT_FAILURE);
}
char *data;
fileRead(data,filename); //does not transfer into char *data
printf("%s",data); //prints nothing but an address
exit(EXIT_SUCCESS);
}