Hi all. This question is about opening a file (regarding sdcard and arduino) from this tutorial.
Can someone help me with understanding 'myfile'? It is an instance of a class known as "FILE". So once the code for opening some arbitrary text file (eg. 'test.txt') is performed, then we can then use the word 'myFile' to access that opened file, right?
The main question I got is related to this line of code: if (myFile) {
Can someone help out to explain how this works, as in 'myFile' becomes treated as a boolean data type? I know it's not magic, but looks like computer magic (for the ones that don't understand how it all works). Thanks in advance for any help with my question here.
myFile = SD.open("test.txt", FILE_WRITE);
// if the file opened okay, write to it:
if (myFile) {
According to this following arduino help document at SD - Arduino Reference .... it says something like SD.open() :
RETURNS a File object referring to the opened file; if the file couldn't be opened, this object will evaluate to false in a boolean context, i.e. you can test the return value with "if (f)".
Can I ask if I understand all this properly? myFile is capable of taking on various 'types' or data types, right?
So if we use SD.open("test.txt", FILE_WRITE); ..... then this code will make "myFile" a boolean, and assign it a logical '1' if the file is successfully opened, and assign it a logical '0' if the file wasn't successfully opened?
File::operator bool() {
if (_file)
return _file->isOpen();
return false;
}
causes File objects to be treated as a bool type (also known by Arduino's type alias "boolean"). Whenever that object is used it runs the above function.
So you could put any code in the library's function and have it return whatever you wanted but the user can use myFile like a bool variable even though it's a function.
Thanks for teaching me all of those things pert, and for your time for helping me understand all of this. That was a huge boost. I understand it now, only because you helped. I wouldn't have known what this is all about otherwise. Much appreciated.
Thanks for explaining again, and for that link with overloaded operators!!