I have began learning C++ for Arduino and have run into some troubles. I have some functions reading/writing to SPIFFS files. Since the code for opening configuration files is common I would want to have a separate function to handle it.
I have come up with following function declaration
ConfigFileOpenStatus DeviceOpenConfigFile(const char *path, File *file);
The function accepts pointer to char array for the file path, and pointer to opened file. I then tried to make following function definition
ConfigFileOpenStatus DeviceOpenConfigFile(const char *path, File *file)
{
if (SPIFFS.exists(path))
{
file = &SPIFFS.open(path, "r+");
return !file ? Failed : Opened;
}
else
{
file = &SPIFFS.open(path, "w+");
return !file ? Failed : Created;
}
}
That did not work as compiler complained with error error: taking address of temporary [-fpermissive] As I understand this means that the file object will be disposed once DeviceOpenConfigFile function returns?
So my question is whether its possible to implement a function in a way where I can get File object reference and release it later?
SPIFFS.open
apparently returnsFile
, by value. The returned value will be a temporary variable available on that line. So taking the address of that one doesn't make any sense, for the same reason asint func (void); ... &func()
doesn't make any sense. It has nothing to do with the surroundingDeviceOpenConfigFile
function.void func (int x) { x = 0; }
doesn't make sense - you change a local variable only, nothing on the caller side gets changed and nothing gets returned to the caller.It would seem that the solution you are looking for is this:
where
file
is allocated on the caller-side.