gpt4 book ai didi

c - 写入文件的 I/O 问题

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:47 25 4
gpt4 key购买 nike

我很难弄清楚为什么这段代码不能正常工作。我正在学习 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”。我猜\00 代表可用的 1024 中留空的所有字节,对吧?我怎样才能防止这种情况发生?

最佳答案

看起来你很期待

readBytes = read(0, buffer, SIZE) < SIZE)

以某种方式在缓冲区中积累东西。它没有。每个后续的 read 都会将它读取的内容放在缓冲区的开头,覆盖之前的 read 读取的内容。

您需要将您的write 放在while block 中——每次读取一次写入,并且只write 与您 >read,否则您将在日志文件中写入垃圾(calloc 的零和/或上次读取的剩余)。

另请注意,虽然您的技术可能在大多数情况下适用于行缓冲输入流,但如果您从文件或管道重定向,则它不会达到您的期望。您应该使用格式化输入函数(例如 getline,如果您的实现有 scanffgets)。

关于c - 写入文件的 I/O 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9239546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com