从文本文件中读取值并将其分配给C中的全局变量(常量)

从文本文件中读取值并将其分配给C中的全局变量(常量),c,file-io,C,File Io,我有一个“config”文件,它只是一个.txt文件,如下所示: 变量名称1 变量名称2 我试图找到一种方法来读取这些值,并将变量_NAME右侧的值分配给全局变量,这些变量在我的程序中将是常量(变量_NAME)。我创建了一个函数,该函数读取文件的内容并将其写入另一个文件,但我不知道如何读取文件中的内容并以某种方式将其存储为程序的全局变量。在此方面的任何指导/资源都将不胜感激! 下面是我的函数readAndWriteFileContents()的主体 您可以有一个structs数组。每个struc

我有一个“config”文件,它只是一个.txt文件,如下所示:

变量名称1

变量名称2

我试图找到一种方法来读取这些值,并将变量_NAME右侧的值分配给全局变量,这些变量在我的程序中将是常量(变量_NAME)。我创建了一个函数,该函数读取文件的内容并将其写入另一个文件,但我不知道如何读取文件中的内容并以某种方式将其存储为程序的全局变量。在此方面的任何指导/资源都将不胜感激! 下面是我的函数readAndWriteFileContents()的主体


您可以有一个
struct
s数组。每个
struct
都将存储变量名及其值,可能同时作为字符串或字符串指针。这是一个运行时作业,还是您正试图从文件数据生成C源代码?@WeatherVane,试图从文件数据生成C课程代码,但不确定这是否可行。谢谢你的结构建议@user3121023 fgets不接受char*str吗?当然可以生成C源代码。
struct
建议用于运行时场景。从输入文件中提取数据后(使用
strtok
?),可以执行类似于
fprintf(cfile,“int%s=%s;\n”,token1,token2)的操作假设需要
int
或类似的值。“将它们分配给…(常量)”是最不清楚的。无法在运行时分配常量。
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);