对于C语言中使用fread出现乱码的解决方法(排除编码问题)

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

// 不要在意使用的是C++,同个道理
int main(){
    const char *filePath = "../test.txt";
    const int BUFFSIZE = 1024;
    char buf[BUFFSIZE];
    FILE *fp = NULL;
    if ((fp = fopen(filePath, "r")) == NULL)
    {
        cout << "error" << endl;
    }
    memset(buf, 0,sizeof(buf));
    fread (buf, sizeof (char), BUFFSIZE, fp);
    cout << buf << endl;
}

即关键点就是memset(buf, 0,sizeof(buf));,因为读取的完毕后,并不会为buf字符数组添加\0,所以需要我们亲自给fread添加上尾巴\0,让其能作为字符串正常输出。(当然我这个memset的方法完全是暴力初始化,不建议采用)。