gpt4 book ai didi

c++ - 写入文件,st_mtime 不变

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:31:11 27 4
gpt4 key购买 nike

我有一个程序想要检查文件是否已被修改。 regtest 失败,事实上,尽管文件已更改,st_mtime 却没有!此外,外部统计数据也证实了这一点。

我相信 st_mtime 应该改变,因为 stat(2) 说

The field st_mtime is changed by file modifications, for example, by mknod(2), truncate(2), utime(2) and write(2) (of more than zero bytes).

这里有一些 C 代码可以说明这个问题:

#include <assert.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>


void touch(const char *fn, const char *contents)
{
FILE *fp;
assert(fp = fopen(fn, "w"));
fprintf(fp, contents);
fclose(fp);
}


int main( int argc, char *argv[] )
{
struct stat st;
char path[] = "/tmp/foo";
time_t m1, m2;
unsigned int t;

touch(path, "hello\n");
assert(!stat(path, &st));
m1 = st.st_mtime;

touch(path, "hello, world!\n");
t = sleep(2);
assert(!stat(path, &st));
m2 = st.st_mtime;

printf("Sleep remaining: %lu\n", t);
printf("Elapsed modtime=%lu\n", m2 - m1);
}

这里有一些东西可以提供给 bash 以确认它不仅仅是在 C 程序中缓存:

$ while true; do stat /tmp/foo | grep Modify; sleep 1;done

有什么建议吗? Fwiw,这是在这样识别的系统上运行的:

jeff@london:src $ uname -a
Linux london 2.6.32-37-generic #81-Ubuntu SMP Fri Dec 2 20:32:42 UTC 2011 x86_64 GNU/Linux
jeff@london:src $

最佳答案

首先,我强烈建议您不要在 assert 中使用带有副作用的语句。我知道这很方便,如果代码永远不会投入生产也没关系,但这不是好的形式。特别是,如果您定义了 NDEBUGassert 将转换为 noop,条件代码永远不会执行。

现在,问题很可能是您将 sleep 调用放在了两个 touch 调用之后,而不是在它们之间。改变这个:

touch(path, "hello\n");
assert(!stat(path, &st));
m1 = st.st_mtime;

touch(path, "hello, world!\n");
t = sleep(2);
assert(!stat(path, &st));
m2 = st.st_mtime;

touch(path, "hello\n");
int rv = stat(path, &st);
assert(!rv);
m1 = st.st_mtime;

t = sleep(2);

touch(path, "hello, world!\n");
int rv = stat(path, &st);
assert(!rv);
m2 = st.st_mtime;

关于c++ - 写入文件,st_mtime 不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8749543/

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