首页 > 解决方案 > 我的文件中有奇怪的字符。我在 C 语言中使用无缓冲 I/O 流

问题描述

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
  int i, stream;

  for (i = 20; i < 40; i++) {
    if (i % 2 == 0) {

      stream = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
      char *x;
      *x = i;
      write(stream, &x, 1024);

      close(stream);
    }
  }
  return 0;
}

我在文件中有字符,例如:

@^@^@^@^@Z^@^@2@^@^@

标签: cfileunixiostream

解决方案


代码中存在多个问题。

char *x;
*x = i;

这将创建一个不指向任何地方的指针,并立即通过该指针进行写入。未定义的行为。你可能想要这个:

char x = i;

write(stream, &x, 1024);

这将从变量的地址开始写入 1024 个字节x。在原始情况下,x是一个指针,因此它很可能占用 4 或 8 个字节(取决于您的系统分别是 32 位还是 64 位)。通过我上面建议的更改,x是一个单字节变量。

无论哪种情况,都没有 1024 字节的数据要写入。你可能是这个意思:

int main(int argc, char* argv[]) {
  int i, stream;

  for (i = 20; i < 40; i++) {
    if (i % 2 == 0) {

      stream = open(argv[1], O_WRONLY | O_CREAT | O_TRUNC, 0644);
      char x = i;
      write(stream, &x, 1);

      close(stream);
    }
  }
  return 0;
}

推荐阅读