gpt4 book ai didi

c - strtok() 没有按预期工作

转载 作者:太空宇宙 更新时间:2023-11-04 06:58:44 24 4
gpt4 key购买 nike

我正在使用 strtok() 函数在换行符上拆分文件缓冲区,但我得到的结果不是我所期望的。

patient->fullName = strtok(fileContent, "\n");
patient->dateOfBirth = strtok(NULL, "\n");
patient->height = strtok(NULL, "\n");
patient->waistMeasurement = strtok(NULL, "\n");
patient->weight = strtok(NULL, "\n");
patient->comment = strtok(NULL, "\n");

当我将分隔值保存到结构成员中时,除第一个 fullName 之外,每个成员稍后都显示正常。如果我做对了,它会显示地址值。这是输出:

enter image description here

由于我对C还不熟悉,请问如何才能得到这个指针地址所在文件中实际写入的全名?

编辑:

创建fileContent:

FILE *file = fopen(fileName, "r");

fseek(file, 0, SEEK_END);
long size = ftell(file);
rewind(file);

char *fileContent = malloc(size + 1);
fread(fileContent, size, 1, file);

患者:

struct Patient
{
char *fullName;
char *dateOfBirth;
char *height;
char *waistMeasurement;
char *weight;
char *comment;
};

struct Patient *patient = malloc(sizeof(*patient));

patient->fullName = malloc(sizeof(NAME_LENGTH));
patient->dateOfBirth = malloc(sizeof(BIRTHDAY_LENGTH));
patient->height = malloc(sizeof(HEIGHT_LENGTH));
patient->waistMeasurement = malloc(sizeof(WAIST_LENGTH));
patient->weight = malloc(sizeof(WEIGHT_LENGTH));
patient->comment = malloc(sizeof(COMMENT_LENGTH));

保存在文件中的文件内容(虽然是加密的):

Qevms Wqspgmg
49.46.5336.
534,9
84,7
28,6
Li'w jygomrk eaiwsqi hyhi!

最佳答案

请注意,malloc() 调用分配的空间都因使用 strtok() 而丢失——您正在泄漏。您需要使用 strcpy() 将字符串复制到分配的空间中。在复制之前,您需要检查是否分配了足够的空间。或者您可以使用 POSIX 函数 strdup()patient->fullName = strdup(strtok(fileContent, "\n"));。 (这有点冒险;我通常会在将 strtok() 的返回值传递给 strdup() 之前检查它的返回值——但这说明了问题。)

此外,因为您正在复制指向 fileContent 的指针,如果您将下一行读入 fileContent,它将更改前一行所指向的字符串的值患者记录。或者,当 fileContent 超出范围并用于其他目的时,数据将再次更改。

关于c - strtok() 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40987927/

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