sd card library question - about opening a file

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) {

This is the relevant code:

operator bool();
File::operator bool() {
  if (_file) 
    return  _file->isOpen();
  return false;
}

Thanks pert! Thanks for that.

According to this following arduino help document at Arduino - SDopen .... 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?

Thanks pert!

I think you understand it correctly.

This code in your sketch:

File myFile = SD.open("test.txt", FILE_WRITE);

creates an object of the SD library's File class.

This code in the library:

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.

A related topic is overloading operators Classes (II) - C++ Tutorials

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!!