简体   繁体   中英

How can i use bool to create a file

Hi can someone help me with this function:

bool createfile (string path);

It is supposed to create a file but my problem is: What exactly the true or false have to do with creating a file?? How can I use it?

The bool is the return type of the function createfile() . Without the definition it is impossible to tell for sure what exactly this value is supposed to be, but often it is used to return if the function was successful in doing what it is supposed to do, in this case, create a file.

What exactly the true or false have to do with creating a file?!

You might want to return true if the file was successfully created or false otherwise.

How can I use it?

This depends on the body of the function and the purpose that you want to use the function for.

Quick answer

To directly answer the "How can I use it" part of your question:
You call it this way:

string path = "/path/to/my/file.txt";
bool returnedValue = createfile(path);

As for "What exactly the true or false have to do with creating a file?!" , like mentionned in the other answers, it might indicate the success or failure of the operation, but you might want to double-check that, because the actual value will depend on the implementation of bool createfile(string path) ...

Comprehensive answer

It seems you need some help interpreting the syntax of bool createfile(string path);

What we need to clarify here is that in c++ (and many other languages), the first word used in the function declaration is the return type .
You could compare this to some arbitrary mathematical function of the following form: here

x = a + b 

In this case, x is the result of the addition function.
Assuming all the elements above are numbers, we could translate this in c++ , like so:

int a = 0;
int b = 5;
int x = a + b;

We could extract the example above in a function (to reuse the addition), like so:

int add(int a, int b)
{
  return a + b;
}

and use it in the following way (with a main to put some execution context around it):

int main()
{
  int x = add(0,5);
  return 0;
}

Here are some other examples of functions:

// simple non-member function returning int
int f1()
{
    return 42;
}
 
// function that returns a boolean
bool f2(std::string str)
{ 
    return std::stoi(str) > 0;
}

You'll find more details here . It might seem like a lot to take in (the page is dense with information), but it is a true reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM