2010-03-27 52 views
2

我想寫一個函數,它將讀取文本文件中的值並將它們寫入變量。例如我的文件是:從文件中讀取選項

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

並且我具有與該行中第一個單詞相同的變量。 那麼如何使功能從文件中讀取數據,並做某事像這樣:

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

我不知道甚至如何開始寫吧...

+0

「do sth like this:」是指將它寫入另一個C源文本文件或什麼? 在這種情況下,您必須使用轉義引號。 fprintf(myfile,「char * mysql_server = \」localhost \「; \ n」); – 2010-03-27 22:22:39

回答

1

要打開和關閉一個文件,可以使用:

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 

對於閱讀論據,你問 - 這似乎是一個簡單的例子,和的fscanf是一個簡單的解決方案。格式將是這樣的:

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

在scanf上閱讀 - 大量的文檔可用。但它的要點是,fscanf(FILE* f, char* format, void* p_arg1, void* p_arg2...)可以讓你從文件中讀取參數到你提供的指針中,格式與printf()非常相似。

+0

您應該限制fscanf讀取的字符,以避免溢出。 – 2010-03-28 11:29:57

1

爲您簡單的例子:

#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 ... 
    } 
} 

對於更復雜的情況檢查libconfig或類似。

+0

難道你不是這個意思:'mysql_server = xstrdup(value)'etc? – 2010-03-27 23:44:27

+0

是的,編輯過,ty。 – clyfe 2010-03-28 11:24:27

+0

更正:strcmp retval必須被檢查== 0 – ostefano 2011-08-11 17:30:57