linux c 追加写文件内容,如何在C中追加到文件,在Linux上使用O_APPEND模式打开?

这是家庭作业的一部分.好吧,我的作业无法正常工作,所以我已经把一个片段拿出来并开始用它来弄清楚什么是错的.

在C语言的Linux上我试图打开/创建一个文本文件,给它写一些东西,关闭它,在读/写和追加模式下打开它,然后在它的末尾添加任何东西(在这个例子中,字符串",老兄").但是没有附加任何内容,但write方法也没有抛出错误.我不确定是什么.

这是代码:

#include

#include

#include

#include

#include

#include

#include

#define BUFFSIZE 4096

int main(){

mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH;

int fd = open("tempfile.txt", O_RDWR | O_CREAT, mode);

char buf[BUFFSIZE] = {'t', 'h', 'y', ' ', 'f', 'a', 'l', 'l'};

size_t n = sizeof(buf);

if(write (fd, buf, n) < 0){

printf("Error in write\n");

printf("%s", strerror(errno));

return 1;

}

close(fd);

int fd2 = open("temp

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我来回答你的问题。下面是一个示例代码,可以实现你所需的功能: ```c #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <time.h> #define FILENAME "test.txt" int main() { int fd; int i = 0; char buf[256]; time_t t; struct tm *tm; signal(SIGINT, SIG_IGN); // 忽略 Ctrl-C 信号 while (1) { if ((fd = open(FILENAME, O_WRONLY | O_CREAT | O_APPEND, 0644)) < 0) // 打开文件,若文件不存在则创建 { perror("open"); exit(1); } t = time(NULL); tm = localtime(&t); sprintf(buf, "%d %04d-%02d-%02d %02d:%02d:%02d\n", ++i, tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec); // 按要求格式化数据 if (write(fd, buf, strlen(buf)) < 0) // 数据 { perror("write"); exit(1); } close(fd); // 关闭文件 sleep(1); // 等待 1 秒 } return 0; } ``` 在这个程序,我们使用了 `open()` 函数打开文件,并使用了 `O_WRONLY`、`O_CREAT`、`O_APPEND` 参数来指定打开文件模式。其,`O_WRONLY` 表示只模式,`O_CREAT` 表示如果文件不存在则创建,`O_APPEND` 表示在文件末尾追加数据。文件权限使用了 `0644`,表示文件所有者有读权限,其他用户只有读权限。 我们使用了 `time()` 函数和 `localtime()` 函数获取当前时间,并使用了 `sprintf()` 函数将数据按要求格式化。然后使用 `write()` 函数将数据文件,最后使用 `close()` 函数关闭文件。 程序使用了一个无限循环,每次循环都会打开文件入数据、关闭文件,并等待 1 秒。如果程序接收到了 Ctrl-C 信号,会忽略该信号,继续循环。这里没有进行错误处理,你可以根据需要进行修改。 当下次再次启动程序时,会追加到原文件之后,并且序号能够接续上次的序号。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值