文本文件转换为动态数组

text file into dynamic array

提问人:wictor33 提问时间:11/14/2022 最后编辑:Andreas Wenzelwictor33 更新时间:11/14/2022 访问量:43

问:

我从 youtube 视频中找到了这段代码,它看起来很棒,但是当我重写它时,它不起作用。它应该读取一个文本文件并将其放入动态数组中,但输出是无意义的,并且输出看似随机的小写和大写字母和符号,如“?”和“!”。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE* file;
    file = fopen("C:\\Users\\varga\\CLionProjects\\untitled3\\subor.txt", "r");
    if (file == NULL)
    {
        printf("Error");
    }

    size_t total = 0;
    char c;
    while ((c = getc(file)) != EOF)
    {
        fgetc(file);
        total++;
    }

    char *string = malloc(total);
    rewind(file);
    size_t index = 0;

    while ((c = getc(file)) != EOF)
    {
        string[index] = fgetc(file);
        index++;
    }

    string[index - 1] = "\0";

    fclose(file);

    printf("File concents: \n\n");
    printf("%s\n", string);

    free(string);
    return 0;
}
阵列 C 动态 malloc

评论

0赞 Andreas Wenzel 11/14/2022
我建议你读一读:在什么情况下,我可以在我的问题中添加“紧急”或其他类似短语,以获得更快的答案?我已从问题中删除了多余的信息。
2赞 Some programmer dude 11/14/2022
请注意,getchar 返回一个 int。在将返回值与值进行比较时,这一点相当重要。如果你运气不好,这种比较实际上是行不通的,你会得到一个无限循环。intEOF
2赞 Some programmer dude 11/14/2022
另一方面,您的阅读循环每次迭代都会读取两个字符。从输入文件中跳过每两个字符。
2赞 Some programmer dude 11/14/2022
并且不会做你所期望的。请花点时间思考一下 和 之间的区别。string[index - 1] = "\0"'\0'"\0"
0赞 Andreas Wenzel 11/14/2022
打开文件失败时,将打印一条错误消息,但继续执行程序,就好像它已成功一样。我建议你立即退出程序,例如在 .exit( EXIT_FAILURE );printf("Error");

答: 暂无答案