我想编写一个函数,从文本文件中读取值并将它们写入变量。例如我的文件是:
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;
...
我什至不知道如何开始写它......
最佳答案
要打开和关闭文件,您可以使用:
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() 非常相似。
关于c - 从文件中读取选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2531088/