c - 从文本文件中读取值并将它们分配给 C 中的全局变量(常量)
问题描述
我有一个“配置”文件,它只是一个 .txt 文件,布局如下:
变量名 1
变量名 2
我正在尝试找到一种方法来读取这些值并将 VARIABLE_NAME 右侧的值分配给全局变量,这些变量在我的程序中将是常量 (VARIABLE_NAME)。我创建了一个函数,它读取文件的内容并将其写入另一个文件,但我对如何读取文件中的内容并以某种方式将它们存储为我的程序的全局变量感到困惑。非常感谢任何有关这方面的方向/资源!这是我的函数 readAndWriteFileContents() 的主体
FILE *ptr_file;
FILE *ptr_logFile;
// allocate memory for the info stored in the config file
char *configFileContent = (char*) malloc(sizeof(char));
// open the files to use
ptr_file = fopen("config.txt", "r");
ptr_logFile = fopen("log.txt", "w");
// if file was not opened successfully, print an error then exit
if (!ptr_file) {
printf("ERROR: No file found.");
exit(1);
}
// read the file, printing each line – and write that input file's contents to a log file
while (fgets(configFileContent, sizeof configFileContent, ptr_file) != NULL) {
// print file contents read
printf("%s", configFileContent);
// writes config file's contents to ptr_logFile
fprintf(ptr_logFile, "%s", configFileContent);
}
// free the memory used to read the config file
free(configFileContent);
// close the files
fclose(ptr_file);
fclose(ptr_logFile);
解决方案
推荐阅读
- python - Don't understand cause of this AttributeError: '_Screen' object has no attribute 'setimage'
- javascript - 如何用两个对象读取 Json?
- python - 检查python中是否存在系统范围内的互斥锁
- c++ - 如何限制我连续拥有的数字数量?
- java - 如何创建弹出消息以提醒用户字段不完整?
- java - 如何使用比较器
作为通用 SortedDoublyLinkedList 中的参数 - java - 如果鼠标正在移动,则重新启动计时器
- polymer - 什么是 Polymer 3 中纸质菜单和纸质子菜单的正确替换?
- python - 动态制作文件名时不理解此字符串连接错误
- ios - 在 Swift 中将单词转换为数字