我想写一个函数,它将从文本文件中读取值并将其写入变量例如,我的文件是:

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

阅读大量可用的文件但其要点是,fscanf(FILE* f, char* format, void* p_arg1, void* p_arg2...)允许您将参数从文件读取到所提供的指针中,其格式与printf()非常相似。

关于c - 从文件中读取选项,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2531088/

10-11 22:24
查看更多