开发者

Read options from file

开发者 https://www.devze.com 2022-12-24 04:02 出处:网络
I would like to write a function which will re开发者_Go百科ad values from a text file and write them to variables. For example my file is:

I would like to write a function which will re开发者_Go百科ad values from a text file and write them to variables. For example my file is:

mysql_server localhost
mysql_user root
mysql_passworg abcdefg
mysql_database testgenerator
log log.txt
username admin
password abcd

and I have the same variables as the first word in the line. So how to make the function read data from file and do sth like this:

char *mysql_server = localhost;
char *mysql_user = root;
...

I have no idea even how to start writing it...


To open and close a file, you use:

strFName = "my_file.txt"
FILE* my_file;
my_file = fopen(strFName, "r"); // "r" - read option. Returns NULL if file doesn't exist
/** operations on file go here **/
fclose(my_file); // must be called when you're done with the file

For reading arguments as you ask - this seems a simple case, and fscanf is a simple solution. Format will be something like this:

char arg1[30], arg2[30];
fscanf(my_file, "%s %s", arg1, arg2); // reads two strings - one into arg1, the second into arg2

Read up on scanf - plenty of documentation available. But the gist of it is, fscanf(FILE* f, char* format, void* p_arg1, void* p_arg2...) lets you read arguments from a file into the pointers you provide, with format very similar to that of printf().


For your simple case:

#include <stdio.h>
#include <string.h>

char *xstrdup(const char *string) {
  return strcpy(malloc(strlen(string) + 1), string);
}


char *mysql_server;
char *mysql_user;
...

FILE * f = fopen("/path/to/file.conf", "r");
while(!feof(f)) {
    if(fscanf(f, "%s %s", &variable, &value) == 2){
       if(strcmp(variable, "mysql_server") == 0){
           mysql_server = xstrdup(value);
       } else if(strcmp(variable, "mysql_user") == 0) {
           mysql_user = xstrdup(value);
       } else ...
    }
}

For a more complex case check libconfig or similar.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号