gpt4 book ai didi

c - 如何用C重写文件的全部内容

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:24:20 24 4
gpt4 key购买 nike

我有用于 ajax 源的文本文件。浏览器每 1 秒发送一次 ajax 请求以从此文件中读取实际数据。我也有写在 C 上的守护进程,它将实际数据写入该文件。看下面的代码:

static void writeToFile_withLock(const char * file_path, const char * str)
{
struct flock fl = {F_WRLCK, SEEK_SET, 0, 0, 0 };
int fd;
const char * begin = str;
const char * const end = begin + strlen(str);

fl.l_pid = getpid();

if ((fd = open(file_path, O_CREAT | O_WRONLY)) == -1) {
perror("open");
exit(1);
}
printf("Trying to get lock...\n");
if (fcntl(fd, F_SETLKW, &fl) == -1) {
perror("fcntl");
exit(1);
}
printf("got lock\n");

printf("Try to write %s\n", str);
while (begin < end)
{
size_t remaining = end - begin;
ssize_t res = write(fd, begin, remaining);
if (res >= 0)
{
begin += res;
continue; // Let's send the remaining part of this message
}
if (EINTR == errno)
{
continue; // It's just a signal, try again
}
// It's a real error
perror("Write to file");
break;
}

fl.l_type = F_UNLCK; /* set to unlock same region */

if (fcntl(fd, F_SETLK, &fl) == -1) {
perror("fcntl");
exit(1);
}

printf("Unlocked.\n");

close(fd);

}

问题:如果以前的数据 > 新数据,那么旧的几个符号保留在文件的末尾。

我如何重写完整的文件内容?

提前致谢。

最佳答案

将 O_TRUNC 添加到 open() 调用中...

O_TRUNC

If the file already exists and is a regular file and the open mode allows writing (i.e., is O_RDWR or O_WRONLY) it will be truncated to length 0. If the file is a FIFO or terminal device file, the O_TRUNC flag is ignored. Otherwise the effect of O_TRUNC is unspecified.

关于c - 如何用C重写文件的全部内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15575231/

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