0

I want to open a file, write to it, and properly check all error possibilities with QFile. I have found how to this with std::ofstream:

std::ofstream f(...);
//  all sorts of output (usually to the `std::ostream&` in a
//  function).
f.close();
if ( ! f ) {
    //  Error handling.  Most important, do _not_ return 0 from
    //  main, but EXIT_FAILUREl.
}

Can I do error checking in a similar way if I use operator<<() with QFile?

What I have found is to use the write method and compare the return value with the length of string to write.

robert
  • 3,539
  • 3
  • 35
  • 56

1 Answers1

0

If you want to use the operator<< to write you'll need a stream like QDataStream or QtextStream. And after each write you can check the stream status:

QFile file("out.txt");
if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
    return;

QTextStream out(&file);
out << "The magic number is: " << 42 << "\n";
if (out.status() != QTextStream::Ok)
{
   // FAILED
}
Mihayl
  • 3,821
  • 2
  • 13
  • 32
  • It can not happen that no actual write happens because of buffering, and the error may occur later when the write is actually performed? – robert Feb 06 '18 at 08:43
  • I think it could, but it's difficult because there are multiple levels of buffering and platform specific (see QIODevice::Unbuffered). You can try flushing and sync-ing. Or maybe even transactions. – Mihayl Feb 06 '18 at 08:53
  • @A.A, to that question, its always better to write ... `<< endl` instead of ... `<<"\n"`, as it would flush the stream and the device instantly. – Mohammad Kanan Feb 06 '18 at 08:57
  • @MohammadKanan. I prefer to explicitly call flush because `endl` makes the whole i/o unnecessary slow, except you really need it. But it doesn't help with the kernel buffers on linux for example. – Mihayl Feb 06 '18 at 09:01
  • @A.A, I have no idea why _slow_ lness could be experienced, but in _Qt_ , `&endl` is equivalent to `stream << '\n' << flush;` .. instead of doing each separately – Mohammad Kanan Feb 06 '18 at 09:06
  • @MohammadKanan [CppCon 2017: Dietmar Kühl “The End of std::endl”](https://www.youtube.com/watch?v=6WeEMlmrfOI) – Mihayl Feb 06 '18 at 09:11
  • @A.A, yes this is what I said in my comment, it would `flush()` ... your answer to _robert_ above was _You can try flushing_. – Mohammad Kanan Feb 06 '18 at 09:17