Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
这是为什么;“读取文件”;功能I';你在Linux和Windows中用C创建的应用程序的行为有什么不同?_C - Fatal编程技术网

这是为什么;“读取文件”;功能I';你在Linux和Windows中用C创建的应用程序的行为有什么不同?

这是为什么;“读取文件”;功能I';你在Linux和Windows中用C创建的应用程序的行为有什么不同?,c,C,我使用这个函数来读取包含字符串的文本文件,这些字符串被读入并插入到AVL树中。在Windows中一切都运行得很好,但是一旦我尝试在Linux中运行它,就会产生完全不同的结果(我得到一堆冗余节点,它们的键只是空白)。有人能解释为什么会这样吗 node *read_file(char *list_name) { char array[255]; char *token = NULL; node *found = NULL; node *tree = NULL;

我使用这个函数来读取包含字符串的文本文件,这些字符串被读入并插入到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尊重unix(或linux)中使用
stdio
时遇到问题,只需始终使用
b
说明符来调用
fopen(3)
即可。unix中的行终止符由单个
\n
字符组成,而windows中的行终止符由一系列
\r\n
字符组成。windows端口采用的解决方案包括允许您为
fopen(3)
调用指定
“rt”
,而不是
“r”
,因此
\r
在传递给调用代码之前会被过滤掉。也许您的问题将通过使用<代码> RT > <代码>而不是<代码>“r”<代码>(POSIX规范允许这个标志在UNIX中使用,但是忽略它,所以使用它总是无害的),还有另一个<代码>“B”< /C> >说明符,它允许您将文件视为二进制文件。(所以消除所有
\r
字符的转换没有完成。这主要是指二进制文件。

字符数组[255];
应该是
字符数组[255+1];
@xing:我不这么认为;
fopen(…,“r”)
是“文本模式”并且应该正确处理这种区别。@xing:您的解决方案成功了,谢谢!我在Windows中创建了原始文本文件,然后将它移植到一个tar文件中到Linux,这样就可以解释一切了。@wallZ由于null char.nvm,根据
fgets
文档:
n,我错了− 这是要读取的最大字符数(包括最后的空字符)。通常使用作为str传递的数组长度。