打开HDF5文件而不修改文件时间戳

问题描述 投票:0回答:2

我目前正在 R 中编写一个函数,用于将 Linux 计算机上的外部程序(在

HDF5
中)的输出转换为不同的文件格式。由于我的管道的结构方式,我需要保留时间戳(主要是为了重现性目的)。

我的函数目前只是包装

rhdf5::H5Fopen()
(带有额外的数据转换)

function(path_to_file){
  data <- rhdf5::H5Fopen(path_to_file,
    # preserve original file structure
    native = TRUE
  )

  data <- as.data.frame(data[["slot1"]])

  return(data)
}

但是,这会导致每次我通过该函数读取文件时时间戳(上次修改文件的时间)都会被修改。有没有办法在打开文件时保留原始时间戳?谢谢

r hdf5 rhdf5
2个回答
1
投票

通过在打开之前获取修改时间并在最后重置它来进行黑客攻击。

function(path_to_file){
  mtime <- file.info(path_to_file)$mtime
  on.exit({
    Sys.setFileTime(path_to_file, mtime)
  })

  data <- rhdf5::H5Fopen(path_to_file,
    # preserve original file structure
    native = TRUE
  )

  data <- as.data.frame(data[["slot1"]])

  return(data)
}

0
投票

如果您以只读模式打开文件,则时间戳不会被修改,例如

library(rhdf5)

h5file <- '/tmp/h5ex_t_array.h5'
file.mtime( h5file )
#> [1] "2022-06-27 15:23:43 CEST"

fid <- rhdf5:::H5Fopen( h5file, flags = 'H5F_ACC_RDONLY' )
H5Fclose(fid)
file.mtime( h5file )
#> [1] "2022-06-27 15:23:43 CEST"

fid <- rhdf5:::H5Fopen( h5file )
H5Fclose(fid)
file.mtime( h5file )
#> [1] "2024-02-08 12:24:53 CET"

请记住,在 HDF5 中,您应该始终将打开操作与关闭配对,否则最终会出现潜在的文件锁定问题和内存泄漏。在这种情况下,那就是

H5Fclose()

使用

h5read()
可能会更容易,它默认使用只读并自动处理文件关闭。

© www.soinside.com 2019 - 2024. All rights reserved.