Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. How do I correctly use QFile::open() and QFile::close()?
Forum Update on Monday, May 27th 2025

How do I correctly use QFile::open() and QFile::close()?

Scheduled Pinned Locked Moved Unsolved General and Desktop
qfileopenclose
5 Posts 3 Posters 21.1k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • A Offline
    A Offline
    alogim
    wrote on 6 Mar 2016, 16:03 last edited by
    #1

    My question is very simple. Suppose I have:

    QString fileName = QString("../somefile.conf");
    QFile file(fileName);
    

    Now, I know there exists a very nice method to check if a file exists. Suppose that, if the file does not exist, I want my app to try to create an empty one:

    if (!file.exists())
    {
      std::cerr << "File " << fileName.toStdString() << " does not exist.\n => Trying to create an empty one...\n" << std::endl;
      if (!file.open(QIODevice::ReadWrite))
      {
        std::cerr << "Unable to create empty file " << fileName.toStdString() << "\n =>" << strerror(errno) << "\n" << std::endl;
        return;
      }
    }
    

    Now, suppose

    • my app wasn't able to create an empty file due, for example, to insufficient permissions: shall I call file.close() anyway?
    • my app was able to create an empty file: shall I call file.close()?

    The I want to add some text to the file, but I do not want to interact with it here: I pass the file name to a function which is taking care of it.

    processFile(fileName);
    

    processFile is a simple function that adds some text to it:

    void processFile(const QString& fileName)
    {
      QFile file(fileName);
      file.open(QIODevice::WriteOnly);
    

    Now, because of all the previous checks, I shouldn't have to check if file exists or if I can open it, right?

      QTextStream out(&file);
      out << "Hello, world!\n";
    } 
    

    Where shall I write file.close()? Before writing on it, or after?
    Docs aren't clear at all. In fact, in several examples, they do not call close() at all. Perhaps because when the QFile object is destroyed, it gets closed too? What about my case, in which I need to close it in order to let another function open it?

    K 1 Reply Last reply 6 Mar 2016, 17:17
    0
    • A alogim
      6 Mar 2016, 16:03

      My question is very simple. Suppose I have:

      QString fileName = QString("../somefile.conf");
      QFile file(fileName);
      

      Now, I know there exists a very nice method to check if a file exists. Suppose that, if the file does not exist, I want my app to try to create an empty one:

      if (!file.exists())
      {
        std::cerr << "File " << fileName.toStdString() << " does not exist.\n => Trying to create an empty one...\n" << std::endl;
        if (!file.open(QIODevice::ReadWrite))
        {
          std::cerr << "Unable to create empty file " << fileName.toStdString() << "\n =>" << strerror(errno) << "\n" << std::endl;
          return;
        }
      }
      

      Now, suppose

      • my app wasn't able to create an empty file due, for example, to insufficient permissions: shall I call file.close() anyway?
      • my app was able to create an empty file: shall I call file.close()?

      The I want to add some text to the file, but I do not want to interact with it here: I pass the file name to a function which is taking care of it.

      processFile(fileName);
      

      processFile is a simple function that adds some text to it:

      void processFile(const QString& fileName)
      {
        QFile file(fileName);
        file.open(QIODevice::WriteOnly);
      

      Now, because of all the previous checks, I shouldn't have to check if file exists or if I can open it, right?

        QTextStream out(&file);
        out << "Hello, world!\n";
      } 
      

      Where shall I write file.close()? Before writing on it, or after?
      Docs aren't clear at all. In fact, in several examples, they do not call close() at all. Perhaps because when the QFile object is destroyed, it gets closed too? What about my case, in which I need to close it in order to let another function open it?

      K Offline
      K Offline
      KeithS
      wrote on 6 Mar 2016, 17:17 last edited by
      #2

      @alogim

      You can use the QFileInfo class rather than QFile. Give the filename in the constructor, and check exists() for the file existance, and isWritable() to check if you can write to it. Then in your processFile(fileName) function you can go ahead and open the file in write mode. Write to it, the close it when you are done with it.

      btw opening a non-existant file with QIODevice::ReadWrite mode does not appear what you want as if the file does not exist, it can be opened in write mode but not read mode.

      1 Reply Last reply
      0
      • A Offline
        A Offline
        alogim
        wrote on 6 Mar 2016, 17:37 last edited by
        #3

        @KeithS
        Docs clearly say that in "[...] WriteOnly or ReadWrite mode, if the relevant file does not already exist, this function will try to create a new file before opening it."
        Besides, OpenMode ReadWrite says that it is equivalent to ReadOnly | WriteOnly, that is The device is open for reading and writing.

        By the way, that's exactly what I want: if the file does not exist, try to create it.

        K 1 Reply Last reply 7 Mar 2016, 09:34
        0
        • A alogim
          6 Mar 2016, 17:37

          @KeithS
          Docs clearly say that in "[...] WriteOnly or ReadWrite mode, if the relevant file does not already exist, this function will try to create a new file before opening it."
          Besides, OpenMode ReadWrite says that it is equivalent to ReadOnly | WriteOnly, that is The device is open for reading and writing.

          By the way, that's exactly what I want: if the file does not exist, try to create it.

          K Offline
          K Offline
          KeithS
          wrote on 7 Mar 2016, 09:34 last edited by
          #4

          @alogim

          Ah, I missed the virtual function open() bit.

          Still don't quite see the point trying to open a non-existant file in read mode though; there's nothing to read! if it doesn't exist, you only need to check if it's writeable.

          1 Reply Last reply
          0
          • K Offline
            K Offline
            kshegunov
            Moderators
            wrote on 7 Mar 2016, 17:15 last edited by kshegunov 3 Jul 2016, 17:16
            #5

            Hello,

            my app wasn't able to create an empty file due, for example, to insufficient permissions: shall I call file.close() anyway?

            No you're not required to.

            my app was able to create an empty file: shall I call file.close()

            Again, you're not required to. You can call it if you wish, but by default the QFile instance will close the file when it goes out of scope. Moreover calling close() on an unopened file is permitted, but it does nothing.

            The I want to add some text to the file, but I do not want to interact with it here: I pass the file name to a function which is taking care of it.

            Don't reopen the file on each write, it's a somewhat heavy operation. Have a member variable, open it once and write as much as you'd like.

            Now, because of all the previous checks, I shouldn't have to check if file exists or if I can open it, right?

            Wrong. No one is guaranteeing you that the file exists. On windows a file will (usually) be locked when opened, but on Linux the user can delete it even while you're writing onto it. So don't skip the checks. Also as I mentioned above, don't reopen the file on each write.

            Kind regards.

            Read and abide by the Qt Code of Conduct

            1 Reply Last reply
            0

            1/5

            6 Mar 2016, 16:03

            • Login

            • Login or register to search.
            1 out of 5
            • First post
              1/5
              Last post
            0
            • Categories
            • Recent
            • Tags
            • Popular
            • Users
            • Groups
            • Search
            • Get Qt Extensions
            • Unsolved