c++ - 如果我写一个字符串,fprintf 会将 '\0' 写入文件吗?

标签 c++

我写了下面的代码来理解文件操作。

#include "stdafx.h"
#include <iostream>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    FILE *fp = fopen("c:\\te_st.txt", "w+");

    fprintf(fp, "aa");

    char *buf = new char[4];

    fseek(fp, 0, SEEK_SET);

    int bytes = fscanf(fp, "%s", buf);

    cout << bytes << " " << buf << endl;

    fclose(fp);

    delete buf;

    return 0;
}

我怀疑 fprintf() 是否写入字符“a”、“a”和“\0”或“a”和“a”。当我使用 fscanf 从文件读取后打印输出时,显示了“aa”。但是当我使用 fread() 从文件中读取字节时,如下所示,

fread(buf, 3, 1, fp);

“aa”和一些垃圾字符正在显示。谁能告诉我有什么区别?

最佳答案

does fprintf write '\0' in to the file if I write a string?

没有。
下面的代码将“aa”写入文件。

FILE *fp = fopen("c:\\te_st.txt", "w+");

    fprintf(fp, "aa");

当我们以十六进制模式查看文件时,我们发现它没有打印任何空终止符:

6161

关于c++ - 如果我写一个字符串,fprintf 会将 '\0' 写入文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31223203/

相关文章:

绑定(bind)对象函数时出现 C++ 异步错误

c++ - 错误地尝试重新安置引用的代码示例

c++ - 如何从 char * 中删除换行符?

c++ - 模板函数 - 模板是否覆盖普通函数

c++ - 面向 C/C++ 开发人员的 Eclipse IDE : "invalid arguments" error displayed by mistake?

c++ - Node : Why nodejs c++ addon is so slow?

c++ - 调试 C++ 代码

c++ - 将本地结构传递给 count_if

c++ - 对大小为 n 的数组进行排序

c++ - 在编译时加密/混淆字符串文字