tags:

views:

59

answers:

3

Currently, I'm using ReadFile() and WriteFile() APIs to write & read from file. are there any API functions to replace/edit text if the data is large enough to be written again? I only heard about SetFilePointer() but i'm not quite sure how to use it to replace the text from a file.

For example, select a string/char from file say, value '0' of Key2.

Key1 = 0
Key2 = 0

and change it to '1'.

Key1 = 0
Key2 = 1

+1  A: 

There are lots of APIs for random access to files. They are all almost completely unsuitable for dealing with text files.

Consider if instead of changing 1 digit, you changed from 1 to 2 - i.e. from 1" to "20" you would have to implement not only the "efficient" random access way of doing things, but also the "inefficient" re-write the file way. As you only ever really want one way of doing things, the "inefficient" one is the one to go for.

anon
which file type would be suitable for such operation in efficient way?
Dave18
A block-structured one. But then you wouldn't be able to edit it with a text editor, which is one of the major requirements for configuration files.
anon
+2  A: 

The functions GetPrivateProfileString and WritePrivateProfileString might be good for this.

Mark Wilkins
This of course works by re-writing the entire file.
anon
@Neil: I assumed this too and didn't mention it because I thought it was obvious. But it turns out that is not the case. I just now called WritePrivateProfileString and used filemon and a network sniffer and found that it does not write the whole file if it does not need to change the length of the key value. On my PC (XP), it only writes 4K when the key size is the same. So, in reality, it can be very efficient. On the other hand, the reading of the data is not so efficient since it has to scan the file to find the update location in the first place.
Mark Wilkins
Well you live and learn! Thanks for the info.
anon
A: 

For text files, it's the best choice to read them into memory, do your work, and write them back. for example, read the file contents into a std::string, look for Key2 = and replace the rest of the line with the new value. Then save the string again. You can use std::ifstream to read from a file without a single WinAPI call.

Alexander Gessler