Valhalla Legends Forums Archive | C/C++ Programming | Strange problem.

AuthorMessageTime
Noodlez
[code]
int loadfile(char path[255], char *data){
FILE *pFile;
char *buffer;
int lSize;
pFile = fopen(path,"rt");
if(pFile!=NULL){
fseek(pFile, 0, SEEK_END); /
lSize = ftell(pFile);
rewind(pFile);

data = new char[lSize];
if (data==NULL) return 2;
fread(data,1,lSize,pFile);
fclose(pFile);
return 0;
}
return 1;
}
[/code]

Best way to explain the problem:

[code]
char *strBuffer;
char strPath[255];
if(loadfile(strPath, strBuffer)){
   printf("File contents: %s\n",strBuffer);
}
[/code]

When loadfile function is called, and I output the buffer within the function, the contents of the file are outputted. However, after calling the function, NULL will be displayed. This has had me stumped for 2 days, but I just don't see whats wrong.

Note: The example code is not the code used in my program, however they both do the exact same thing, so it shouldn't matter.
March 27, 2004, 7:22 AM
Skywing
strBuffer will be pointing to uninitialized data. I think you meant to pass a char** instead of a char* judging from your code.
March 27, 2004, 8:04 AM
Moonshine
Yes, you'll need a reference to a pointer, or a pointer to a pointer like skywing said. Or you could always initialize a buffer before the function call (which would require you to have a seperate GetFileSize() type function).

The easiest way to fix this is just change

int loadfile(char path[255], char *data); // Can't pass a pointer to a pointer using one *

to

int loadfile(char path[255], char *&data); // Use a reference to a pointer for easiness' sake (vs. pointer to a pointer)


Also note that you'll need to add a null terminator on the end of that buffer if you're dealing with strings (IIRC).
March 27, 2004, 8:07 AM
Noodlez
Awsome. Thanks Moon & Sky, it works now.
March 27, 2004, 5:42 PM

Search