gpt4 book ai didi

c - 从文件读取数据时无法为字符串赋值

转载 作者:行者123 更新时间:2023-12-01 13:16:37 25 4
gpt4 key购买 nike

我有一个 config.txt 文件,我在其中存储生成一些记录所需的配置,我想通过 C 代码读取配置值并将参数值分配给一些变量。对于整数和 float ,变量被正确分配,但对于字符串类型,每次循环运行时,所有字符串变量都会更新,而不是一个特定的变量。

配置内容。
TIME_LIMIT=2
ING_IP=45.45.45.45
TIMEZONE=GMT+05:30-印度

    const char* timeZone = "GMT+09:00-Tokyo";
const char* ingIp = "null";
int timeLimit = 0;

char *configFileName = argv[++i];

FILE *configFileHandle = fopen(configFileName, "r");

char * line = NULL;

// if (( fgets(line, 500, configFileHandle)) != NULL){
// puts(line);
// }

size_t len = 0;
ssize_t read;

while ((read = getline(&line, &len, configFileHandle)) != -1) {

printf("Line: %s\n", line);
char *parameter = strtok(line, "=");
char *value = strtok(NULL, "=");


char *ptr;
if( (ptr = strchr(value, '\n')) != NULL)
*ptr = '\0';

if( (ptr = strchr(value, '\r')) != NULL)
*ptr = '\0';

if ( strcmp(parameter, "TIME_LIMIT") == 0 ) {
timeLimit = atoi(value);
}else if ( strcmp(parameter, "TIMEZONE") == 0 ) {
timeZone = value;
}else if ( strcmp(parameter, "ING_IP") == 0 ) {
ingIp = value;
}
}

我得到的结果是每次迭代时区值都被 ingIp 的最新值覆盖。我想分配 ingIp = "45.45.45.45"和 timeZone = "GMT+05:30-India"。对于 timeLimit,该值已正确分配。

最佳答案

timeZone = value;

这里您没有复制内容,而是让 timeZone 指向 value。因此 timeZone 将指向存储在 value 中的最新内容。

您可以做的是复制内容而不是指针赋值。

使用 strdup

   timeZone = strdup(value);

或者

   timeZone = malloc(strlen(value)+1);
strcpy(timeZone, value);

关于c - 从文件读取数据时无法为字符串赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54250971/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com