我试图获取文件的内容并将其放入字符串中。当我运行我的程序并打印字符串时,我得到了文件的内容,其中包含一些奇怪的字符。
我的代码:
int size = 0;
char ch = 0;
char* content = 0;
FILE* fs = fopen(file, "r");
//getting file's content and put it into a string
while (ch != EOF)
{
ch = (char)fgetc(fs);
size++;
content = myRealloc(content, size);
content[size - 1] = ch;
}
printf("%s", content);
我的真实分配:
char* myRealloc(char* array, int size)
{
char* temp = 0;
temp = realloc(array, size * sizeof(char));
return temp;
}
文件内容:
1,2,3,4
5,6,7,8
a,b,c,d
e,f,g,h
当我打印时:
1,2,3,4
5,6,7,8
a,b,c,d
e,f,g,h ²²²²ר─
最佳答案
在末尾添加空终止字符:
int size = 0;
int ch = 0;
char* content = 0;
FILE* fs = fopen(file, "r");
//getting file's content and put it into a string
while ((ch = fgetc(fs)) != EOF)
{
size++;
content = myRealloc(content, size);
content[size - 1] = (char)ch;
}
size++;
content = myRealloc(content, size);
content[size - 1] = '\0';
print("%s", content);
编辑:此外,正如@achal 所指出的,您正在尝试添加 EOF 字符,因为当您阅读它时,您已经处于 while 循环中。我相应地修改了我的代码。
关于c - 从 C 中的文件获取 str 时出现奇怪的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50239020/