c - 从文件中读取选项

标签 c file

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

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/

相关文章:

c - 如何从文本文件中提取IP地址

c - tsearch() 创建的树是平衡树吗?

vb.net - 使用 SaveFileDialog 将数据保存到文本文件?

c++ - 无法在 C++ 中创建包含日期和时间的文件名

c++ - 当源不可用时,找到 Visual Studio 2015 调试器读取符号定义的位置

c - fprintf C中 '\n'的作用是什么?

c - 从文本文件中读取结构

c - 在检查测试用例中使用文件

ios - iOS文件读写错误

c - 程序集 32 位 - 比较字符