Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
src_corelib_io_qdatastream.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR BSD-3-Clause
3
4#include <QFile>
5
7{
8 {
9 //! [0]
10 QFile file("file.dat");
11 file.open(QIODevice::WriteOnly);
12 QDataStream out(&file); // we will serialize the data into the file
13 out << QString("the answer is"); // serialize a string
14 out << (qint32)42; // serialize an integer
15 //! [0]
16 }
17
18 {
19 //! [1]
20 QFile file("file.dat");
21 file.open(QIODevice::ReadOnly);
22 QDataStream in(&file); // read the data serialized from the file
23 QString str;
24 qint32 a;
25 in >> str >> a; // extract "the answer is" and 42
26 //! [1]
27 }
28
29 {
30 QDataStream stream;
31 //! [2]
32 stream.setVersion(QDataStream::Qt_4_0);
33 //! [2]
34 }
35
36 {
37 int lots_of_interesting_data = 0;
38 //! [3]
39 QFile file("file.xxx");
40 file.open(QIODevice::WriteOnly);
41 QDataStream out(&file);
42
43 // Write a header with a "magic number" and a version
44 out << (quint32)0xA0B0C0D0;
45 out << (qint32)123;
46
47 out.setVersion(QDataStream::Qt_4_0);
48
49 // Write the data
50 out << lots_of_interesting_data;
51 //! [3]
52 }
53}
54
56{
57 int lots_of_interesting_data = 0;
58 int data_new_in_XXX_version_1_2 = 0;
59 int other_interesting_data = 0;
60 int XXX_BAD_FILE_FORMAT = -1;
61 int XXX_BAD_FILE_TOO_OLD = -2;
62 int XXX_BAD_FILE_TOO_NEW = -3;
63
64 //! [4]
65 QFile file("file.xxx");
66 file.open(QIODevice::ReadOnly);
67 QDataStream in(&file);
68
69 // Read and check the header
70 quint32 magic;
71 in >> magic;
72 if (magic != 0xA0B0C0D0)
73 return XXX_BAD_FILE_FORMAT;
74
75 // Read the version
76 qint32 version;
77 in >> version;
78 if (version < 100)
79 return XXX_BAD_FILE_TOO_OLD;
80 if (version > 123)
81 return XXX_BAD_FILE_TOO_NEW;
82
83 if (version <= 110)
84 in.setVersion(QDataStream::Qt_3_1);
85 else
86 in.setVersion(QDataStream::Qt_4_0);
87
88 // Read the data
89 in >> lots_of_interesting_data;
90 if (version >= 120)
91 in >> data_new_in_XXX_version_1_2;
92 in >> other_interesting_data;
93 //! [4]
94
95 return 0;
96}
97void read_data_transaction_example(QFile file, QDataStream in)
98{
99 //! [5]
100 QDataStream out(&file);
101 out.setVersion(QDataStream::Qt_4_0);
102 //! [5]
103
104 //! [6]
105 in.startTransaction();
106 QString str;
107 qint32 a;
108 in >> str >> a; // try to read packet atomically
109
110 if (!in.commitTransaction())
111 return; // wait for more data
112 //! [6]
113}
void read_data_transaction_example(QFile file, QDataStream in)
int read_data_example()
void wrapInFunction()
[16]