首页 > 解决方案 > 从文本文件中读取值并将它们分配给 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);

标签: cfile-io

解决方案


推荐阅读