提问人:wictor33 提问时间:11/14/2022 最后编辑:Andreas Wenzelwictor33 更新时间:11/14/2022 访问量:43
文本文件转换为动态数组
text file into dynamic array
问:
我从 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;
}
答: 暂无答案
评论
getchar
返回一个int
。在将返回值与值进行比较时,这一点相当重要。如果你运气不好,这种比较实际上是行不通的,你会得到一个无限循环。int
EOF
string[index - 1] = "\0"
'\0'
"\0"
exit( EXIT_FAILURE );
printf("Error");