| 1 |
/* gtkmm example Copyright (C) 2002 gtkmm development team |
| 2 |
* |
| 3 |
* This program is free software; you can redistribute it and/or modify |
| 4 |
* it under the terms of the GNU General Public License as published by |
| 5 |
* the Free Software Foundation; either version 2 of the License, or |
| 6 |
* (at your option) any later version. |
| 7 |
* |
| 8 |
* This program is distributed in the hope that it will be useful, |
| 9 |
* but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 |
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 |
* GNU General Public License for more details. |
| 12 |
* |
| 13 |
* You should have received a copy of the GNU General Public License along |
| 14 |
* with this program; if not, see <https://www.gnu.org/licenses/>. |
| 15 |
*/ |
| 16 |
|
| 17 |
#include <giomm.h> |
| 18 |
#include <iostream> |
| 19 |
|
| 20 |
|
| 21 |
int main(int /* argc */, char** /* argv */) |
| 22 |
{ |
| 23 |
Gio::init(); |
| 24 |
|
| 25 |
try |
| 26 |
{ |
| 27 |
auto file = Gio::File::create_for_path("test_output.txt"); |
| 28 |
if(!file) |
| 29 |
std::cerr << "Gio::File::create_for_path() returned an empty RefPtr." << std::endl; |
| 30 |
|
| 31 |
Glib::RefPtr<Gio::FileOutputStream> stream; |
| 32 |
|
| 33 |
//If the file exists already then replace it. |
| 34 |
//Otherwise, create it: |
| 35 |
if(file->query_exists()) |
| 36 |
stream = file->replace(); |
| 37 |
else |
| 38 |
stream = file->create_file(); |
| 39 |
|
| 40 |
if(!stream) |
| 41 |
std::cerr << "Gio::File::create_file() returned an empty RefPtr." << std::endl; |
| 42 |
|
| 43 |
Glib::ustring contents = "This is some test output"; |
| 44 |
const gsize bytes_read = stream->write(contents.raw()); |
| 45 |
|
| 46 |
if(bytes_read) |
| 47 |
std::cout << "File contents written: " << contents << std::endl; |
| 48 |
else |
| 49 |
std::cerr << "Gio::InputStream::write() wrote 0 bytes." << std::endl; |
| 50 |
|
| 51 |
//Close the stream to make sure that changes are written now, |
| 52 |
//instead of just when the stream goes out of scope, |
| 53 |
//though that's the same time in this simple example. |
| 54 |
//For instance, when using Gio::File::replace(), the file is only |
| 55 |
//actually replaced during close() or when the stream is destroyed. |
| 56 |
stream->close(); |
| 57 |
stream.reset(); //Stream can't be used after we have closed it. |
| 58 |
} |
| 59 |
catch(const Glib::Error& ex) |
| 60 |
{ |
| 61 |
std::cerr << "Exception caught: " << ex.what() << std::endl; |
| 62 |
} |
| 63 |
|
| 64 |
return 0; |
| 65 |
} |
| 66 |
|