gpt4 book ai didi

c - 为什么我在 C 中创建的这个 "read file"函数在 Linux 中的行为与在 Windows 中的行为不同?

转载 作者:行者123 更新时间:2023-12-02 02:48:00 25 4
gpt4 key购买 nike

我正在使用此函数读取包含字符串的文本文件,这些字符串被读取并插入到 AVL 树中。在 Windows 中一切正常,但是一旦我尝试在 Linux 中运行它,它会产生完全不同的结果(我得到一堆冗余节点,它们的键只是空格)。谁能解释为什么会这样?

node *read_file(char *list_name)
{
char array[255];
char *token = NULL;
node *found = NULL;
node *tree = NULL;
FILE *file = fopen(list_name, "r");

if (file == NULL)
{
printf("Could not open file\n");
return NULL;
}

while (fgets(array, 255, file) != NULL)
{
token = strtok(array, " \n");
while (token != NULL)
{
found = find_key(token, tree);

if (found == NULL)
{
tree = insert(token, tree);
}
else
{
found->frequency++;
}
token = strtok(NULL, " \n");
}
}

fclose(file);
return tree;
}

最佳答案

如果您在 Windows 中使用 stdio 时遇到问题,请尊重 unix(或 linux),只需始终使用 b 说明符来调用 fopen(3)。 unix 中的行终止符由单个 \n 字符组成,而在 windows 中它们由一系列 \r\n 字符组成。 Windows 端口采用的解决方案包括允许您指定 "rt",而不是 "r"fopen(3) 调用,因此 \r 在将它们传递给调用代码之前被过滤掉。可能你的问题将通过使用 "rt" 而不是 "r" 来解决(Posix 规范允许在 unix 中使用这个标志,但忽略它,所以使用它always 是无害的)还有另一个 "b" 说明符,它允许您将该文件视为二进制文件(因此消除所有 \r 字符的转换不是完成。这主要是指二进制文件。

关于c - 为什么我在 C 中创建的这个 "read file"函数在 Linux 中的行为与在 Windows 中的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53451704/

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