c - 从 C 中的文件获取 str 时出现奇怪的字符

标签 c file debugging printing char

我试图获取文件的内容并将其放入字符串中。当我运行我的程序并打印字符串时,我得到了文件的内容,其中包含一些奇怪的字符。

我的代码:

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/

相关文章:

python - PyCharm 调试器卡在 "Collecting Data"

visual-studio - winRT 异常堆栈中的行号

c - 关于 C 中的文件 io 函数

c - C语言读写文本文件

c - getchar() 等同于 scanf ("%c") 和 putchar() 等同于 printf ("%c") 吗?

c - 如何从随机数生成器返回中间位?

python - 通过网络共享间歇性 'OSError: [Errno 2] No such file or directory'

debugging - 如何配置 Aptana 3 以在 Debug模式下运行我的 Rails 服务器,以便它在断点处停止?

c++ - 如何从 SHBrowseForFolder 函数获取完整路径?

c - 关于 creat() 系统调用模式参数的快速问题