【问题标题】:Extra string written to file by write() in C在 C 中通过 write() 写入文件的额外字符串
【发布时间】:2014-06-01 01:07:44
【问题描述】:

我编写了一个玩具程序来学习如何将二进制文件写入 C 中的文件。我有以下程序将整数 1 和字符串“hello”写入名为“my_log.txt”的文件中,但文件 ' my_log.txt'写入后包含以下内容:hellowrhellowrhellowrhellowrhellowr

我想知道为什么整数(1)丢失了,额外的字符串“wr”是从哪里来的?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <fcntl.h>

int main()
{
    char *filename = "my_log.txt";
    char *content = "hello";
    int i;

    int filedescriptor = open(filename, O_RDWR | O_APPEND | O_CREAT);

    for (i = 0; i < 5; i++)
    {
        printf("written %d \n", i);
        write(filedescriptor, &i, sizeof(int));
        write(filedescriptor, content, sizeof(content));
    }

    close(filedescriptor);

    return 0;
}

我知道如何使用 fopen/fwrite 将二进制文件写入文件,但我只是在测试在 C 中使用 open/write 的可能性。

【问题讨论】:

  • sizeof(content) == sizeof(char*)

标签: c string binary


【解决方案1】:

我在 CodeBlocks(Win 版)中尝试过 - 将整数转换为字符串。 我找不到以“二进制模式”打开写入的方法。在这种情况下不要使用 sizeof(),尝试使用 strlen() 函数来通知字符串的大小。输出: 0hello1hello2hello3hello4hello --- 但如果你想要 hello0hello1hello... 更改 write() 函数的顺序。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <fcntl.h>
#include <sys/stat.h>

int main()
{
    char *filename = "my_log.txt";
    char *content = "hello";
    char buf[10];
    int i;

    int filedescriptor = open(filename, O_RDWR | O_APPEND | O_CREAT);

    for (i = 0; i < 5; i++)
    {
        printf("written %d \n", i);
        itoa(i,buf,10);
        write(filedescriptor, buf, strlen(buf));
        write(filedescriptor, content, strlen(content));
    }

    close(filedescriptor);

    return 0;
}

【讨论】:

  • 注意,当您使用strlen() 获取char *char [] 的长度时,它返回的长度为不包括空终止符的字符串。但是,使用sizeof(char *) 与使用sizeof(char []) 相比不同,因为它将为char * 生成4,但为char [] 生成长度加空终止符。因此,在您的示例 `...strlen(content)); 中,空终止符将不包含在写入中。在这种情况下,它对您有用,但请注意其中的区别,否则它会在某些时候给您带来问题。
【解决方案2】:

你可以换行:

char *content = "hello";  

char content[] = "hello";  

然后是sizeof(content)在该行:

write(filedescriptor, content, sizeof(content));  

将产生足够的空间 (6 BYTES) 来写出 content (hello\0) 的整个长度,而不仅仅是四个字节。

(即在您的原始代码中,sizeof(content) == sizeof(char *) == 4)

【讨论】:

    【解决方案3】:

    您可能只是没有看到您认为自己看到的内容。
    在我的系统上运行你的程序会产生:

    user@user-vm:~$ hexdump -C my_log.txt 
    00000000  00 00 00 00 68 65 6c 6c  01 00 00 00 68 65 6c 6c  |....hell....hell|
    00000010  02 00 00 00 68 65 6c 6c  03 00 00 00 68 65 6c 6c  |....hell....hell|
    00000020  04 00 00 00 68 65 6c 6c                           |....hell|
    00000028
    

    如您所见,您的整数就在那里,作为一个二进制整数(不是 ASCII 值),范围从 0 到 4,这是您指示它执行的操作。

    另外,正如 BLUEPIXY 提到的,sizeof(content) 将返回 4,因为 char* 在大多数系统上是 4 个字节,因此您只写出“hello”的前 4 个字节。

    尝试使用 hexdump 之类的实用程序以 ASCII 格式查看二进制输出。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 2012-05-25
      相关资源
      最近更新 更多