【发布时间】: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*)