[Interest] Simple doubt on file i/o

Mandeep Sandhu mandeepsandhu.chd at gmail.com
Thu Jun 27 08:56:35 CEST 2013


Hi,

I wanted to know if I'm doing file i/o the right way in one of my apps.

I'm writing  a small helper class for one of my applications which is
supposed to store data, in the form of key-value pairs, in a file. This is
very similar to QSettings but w/o any fancy groups/sections that it
provides. So lets assume that I have to use a file based approach only! :)

It provides 2 functions - get(key) and a set(key, value) and they behave
exactly like QMaps equivalent functions, i.e if the key exists, it'll
overwrite the value, else it'll add a new entry. This class takes either a
filename as input or a QFile itself.

Assumptions:There won't be much data written to the file (max 1-2 KB). The
set function will not be called very often (probably once or twice in the
lifetime of the app). The get fxn will be called a little more often.

Here's what I do in the 2 functions (skipping error condition checks keep
it simple):

get(key):
* Open the file in Read-Only mode.
* Parse the data and prepare a QMap of the key-value pairs.
* Close the file
* Return the value for the key

set(key, value):
* Open the file in Read-Only mode.
* Parse the data and prepare a QMap of the key-value pairs.
* Close the file
* Open the file in Write-Only & Truncate mode
* Insert the new key-value in the map
* Write the map
* Close the file

In the set function I'm opening the file twice - once to read it's content
and prepare the map and next I open it in truncate mode as I want to wipe
off the existing data and write the new data afresh.

Is there a simpler way to achieve what I'm doing with a file? I'm assuming
the 2 open-close calls in set() are ok as it won't be called very often.

Thoughts?

Thanks,
-mandeep
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.qt-project.org/pipermail/interest/attachments/20130627/57926c39/attachment.html>


More information about the Interest mailing list