在Mac上的文件夹中提取文件的创建日期和大小?

时间:2017-09-23 11:00:19

标签: r macos

例如,我在一个文件夹中有三个文件。 我想以这种方式提取它们。

file_name create_time size
A         2017-09-11   3MB
B         2017-09-12   2MB
C         2017-09-13   1MB

1 个答案:

答案 0 :(得分:1)

library(Rcpp)

# This likely only works on macOS

# Define a C function to get the creation time
cppFunction(
  includes = c("#include <sys/stat.h>"),
    "
long birth_time_raw(std::string x) {
  struct stat ftime;
  stat(x.c_str(), &ftime);
  return(ftime.st_birthtimespec.tv_sec);
}
",  
  )

# Wrap it in a helper that does some sanity checks
birth_time <- function(x) {
  x <- path.expand(x)
  if (!file.exists(x)) return(NULL)
  as.POSIXct(birth_time_raw(x), origin="1970-01-01 00:00:00")
}

do.call(
  rbind,
  lapply(
    dir("ƒ", full.names = TRUE),
    function(.x) {
      data.frame(
        file_name = basename(.x),
        create_time = as.Date(birth_time(.x)),
        size = sprintf("%3.1fMB", file.size(path.expand(.x))/1024/1024),
        stringsAsFactors=FALSE
      )
    }
  ) 
) -> files_df
## files_df
##   file_name create_time  size
## 1         A  2017-09-20 4.4MB
## 2         B  2017-09-20 4.2MB
## 3         C  2017-09-21 0.0MB