【问题标题】:write C function produces unreadable file写C函数产生不可读的文件
【发布时间】:2021-03-19 16:28:36
【问题描述】:

以下 C 代码生成一个名为 data 的文件:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
    int a[100];
    for (int i = 0; i < 100; ++i) a[i] = i;
    // create file "data", truncate it, open it for write
    // operation, set user permissions to rw
    int fd = open("data", O_CREAT | O_TRUNC |
            O_WRONLY, S_IRUSR | S_IWUSR);
    if (fd < 0)
        perror("encountered open error");
    int length = 100 * sizeof(a[0]);
    if (write(fd, a, length) != length)
        perror("encountered write error");
    if (close(fd) < 0)
        perror("encountered close error");
    return 0;
}

使用catnotepad++ 打开data 文件会显示一些随机输出:

猫数据:

记事本++数据:

但是当我编写一个程序来使用 read C function 读取这个 data 文件时,它确实显示了从 0 到 99 的数字。 这是什么原因?

【问题讨论】:

  • 您正在写入二进制数据而不是文本数据。因此,在文本编辑器/查看器中打开时,它不会显示为您期望的文本。
  • 我尝试在一张显示 cat 命令的输出和一张在 notepad++ 中打开文件数据时添加两张图片。虽然我拖放了图像。出于某种原因,它显示为一个链接。不知道为什么会这样
  • 请尽可能以文字而非图片的形式发布文字。
  • @Amitwadhwa。假设新用户倾向于不阅读网站规则并滥用基础设施。不用担心,较高代表的用户通常会为您编辑图像。
  • 任何 C 编程书籍的文件处理章节都应该解释文本文件和二进制文件之间的区别。推荐阅读。

标签: c write


【解决方案1】:

嗯,cat 的输出显示你的文件包含升序编码的 ASCII 字符,这与你写的一致,notepad++ 确认文件包含从 0 开始的小端整数。

因此该文件包含您编写的内容:前 100 个整数的 二进制 值。如果您希望它包含文本值,则必须使用标准库的格式化输出函数,即printf 系列函数。

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    相关资源
    最近更新 更多