我有一个“ config”文件,它只是一个.txt文件,其布局如下:
VARIABLE_NAME 1
VARIABLE_NAME 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);