如何检查文件是否在埃菲尔铁塔中

时间:2018-12-13 19:38:21

标签: eiffel

feature 

    open_file_sample
        local
            l_file: UNIX_FILE_INFO
            l_path: STRING
        do
            make
            l_path := "/var/log/syslog"
            l_file.update (l_path)
            if l_file.parent_directory.exists and then l_file.parent_directory.is_writtable then
                create l_file.make
            end
             -- AS the above statement doesn't exist!
            check
                syslog_file_exists_and_is_readable: l_file.exists and then l_file.is_readable
            end
        end

这是检查Eiffel中文件是否存在的正确方法吗?

我想知道是否有一种方法不创建2个对象。我将用以下语句完成检查:

  • 定义路径`l_file_path:=“ /some/path/with_file.log”
  • 检查父目录是否存在并有权写入
  • 创建日志文件

4 个答案:

答案 0 :(得分:2)

访问文件系统时的问题是文件或目录的属性在查询时间和要使用它的时间之间可能已更改(即使只是一秒钟的一小部分)。因此,在埃菲尔铁塔中的断言形式如下:

f (a_file: RAW_FILE)
    require
        a_file.is_writable
    do
        a_file.open_write

可能会被违反。在Gobo Eiffel库中,不是选择在实际打开文件之前是否可以在写入模式下打开文件,而是选择了还原方法:尝试打开文件,然后检查文件是否成功打开。

f (a_pathname: STRING)
    local
        l_file: KL_TEXT_OUTPUT_FILE
    do
        create l_file.make (a_pathname)
        l_file.recursive_open_write
        if l_file.is_open_write then
            -- Write to the file.
            l_file.close
        else
            -- Report the problem.
        end

请注意,它不仅使用recursive_open_write,而且使用open_write,因此也会创建路径中缺少的目录。

答案 1 :(得分:1)

您可以使用 {FILE_UTILITIES} .file_exists(the_file_name)

或 (创建{RAW_FILE} .make_with_name(the_file_name))。

答案 2 :(得分:0)

do
  if not l_file.exists then
    print ("error: '" + l_path + "' does not exist%N")
  else
    ...

您可以与此类似

答案 3 :(得分:0)

我的最终解决方案是紧随其后的,并且受到批评者的批评,与更底层的语言和lib(例如bash for ex)相比,我个人觉得它非常复杂

log_file_path: detachable PATH
        -- Attached if can be created
    local
        l_file: UNIX_FILE_INFO
        l_path, l_parent_dir: PATH
        l_fu: FILE_UTILITIES
    do
        create l_fu
        -- Parent directory check
        create l_path.make_from_string ({APP_CONFIGURATION}.application_log_file_path)
        l_parent_dir := l_path.parent
        if not l_fu.directory_exists (l_parent_dir.out) then
            l_fu.create_directory_path (l_parent_dir)
        end
        create l_file.make
        l_file.update (l_parent_dir.out)
        if not l_file.exists or
            l_file.is_access_writable
        then
            io.putstring ("Error: " + log_file_path_string + " parent directory is not writtable and cannot be created")
            check
                parent_dir_exists_and_is_writtable: False
            end
        else
            Result := l_path
        end
    ensure
        file_name_could_be_created: Result /= Void
    end