return string from function
Hi
I have a small fileloading function. The function loads a file passed on to it by a filechooserdlg, within that file, is the name of another file to load....but I don't know how to return it......
Here it is:
Code:
#include "defines.h"
char *loadmap(char *map) {
FILE *file; // pointer to FILE structure
char str[STR_LEN]; // String for holding file content
int ch; // Check for EOF
int i = 0; // Loop counter var
file = fopen(map,"r"); // Open file
while ((ch = fgetc(file)) != EOF){ // Store the content in str
str[i] = ch;
i++;
}
str[i] = '\0';
fclose(file); // Cleanup
return str; // Returned filename - - not working
}
I am calling the loadmap function like this:
Code:
char *filename;
filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
char *map;
map= loadmap(filename);
Can anyone see the error???
Re: return string from function
str is a local variable. It is destroyed after the function returns.
You need to either make str static or dynamically allocate memory and return the pointer, just remember to delete[] it.