我有用于 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);
}
问题:如果以前的数据 > 新数据,那么旧的几个符号会保留在文件的末尾。
如何重写完整的文件内容?
提前致谢。