I am using C language and Linux as my programming platform.
In my sample application. I want to get and set the value of a custom configuration file. Below is the structure of my config file.
idlevalue=5
sleeping=1
Now my problem is I am getting a hard time thinking how to implement the set functionality in my application.
I am planning to get all the contents of the file. Then set the position of the pointer in the specific value then change the value. Then write all the data into the file again.
开发者_JAVA技巧It seem setting a value in the config file is much harder than getting.
Please advice.
There are other closely related questions on SO.
There are libraries such as libconfig that handle this sort of stuff for you.
EDIT: I removed "don't treat as database' realizing you are conceptually treating it that way... The idea is to have an API on top of the config file :)
Write code to parse and read all the variables into memory. When saving the config file, simply save all the variables over again, rather than trying to locate one specific variable and modify just the value of that specific variable.
Something like this would be good:
char *config_file_path = "/foo/bar.conf";
struct config {...} myconfig;
read_config(config_file_path, &myconfig);
// set a value
myconfig.somevalue = 5;
// When re-writing, routine simply over-writes the entire file.
write_config(config_file_path, &myconfig);
You will only need to write the file out when a user saves the config, so it won't be a huge bottleneck in your app to do it this way.
Sure - the hard part is that the data you want to replace might not be the same size as the data you want to replace it with.
The usual solution, particularly for a simple config file, is to simply write out a complete new copy of the config file from memory, containing all the settings. You create a new file under a temporary name, write out the config to it, call fsync()
to sync it to disk, then rename()
it over the old config file. (This procedure means that you won't end up with a corrupted config file, even if your application or the computer crashes while writing the config file).
As per me obviously getting the data from a file is easier. For changing the values there is one easier solution that you have all the data in some structure and when you want to change some values change them in structure and then copy the whole structure back to file.
In case there was only one change and you are not willing to write the whole data back to the file, you can modify only that value you want by reading a file in "append" mode and seek to the name of your name-value pair and then change the value. It would take a little more effort to implement it than just copying all the data again to file but a its a better way to do what you want.
精彩评论