【发布时间】:2012-02-11 10:41:13
【问题描述】:
我很难弄清楚为什么这段代码不能正常工作。我正在学习 I/O 操作的基础知识,我必须想出一个 C 程序,它在“log.txt”文件上写入标准输入给出的内容,当输入“停止”字时,程序必须停止.
所以我的代码是:
#include "main.h"
#define SIZE 1024
int main(int argc, char *argv[])
{
int fd;
int readBytes;
int writBytes;
char *buffer;
if ((fd = open("log.txt", O_WRONLY|O_APPEND)) < 0)
{
perror("open");
}
buffer = (char *) calloc (SIZE, sizeof(char));
while ((readBytes = read(0, buffer, SIZE) < SIZE)&&(strncmp(buffer, "stop", 4) != 0));
if ((writBytes = write(fd, buffer, SIZE)) < 0)
{
perror("write");
}
if ((close(fd)) < 0)
{
perror("close");
}
}
如果我输入:
this is just a text
stop
输出是
stop
is just a text
如果我输入多个句子:
this is just a text
this is more text
and text again
stop
这是记录的内容:
stop
ext again
xt
t
此外,如果我尝试从 vim 或文本编辑器编辑 log.txt 文件,我可以看到 '\00's。我猜 \00 代表 1024 可用的所有空字节,对吧?我怎样才能防止这种情况发生?
【问题讨论】:
标签: c io system-calls