跨平台鏡像檔案大小一樣嗎?

跨平台鏡像檔案大小一樣嗎?

我的應用程式需要知道 *.png 圖像檔案的確​​切檔案大小(位元組)。這在 Linux 上完全符合預期:

% !TeX TS-program = lualatex
% !TeX encoding = UTF-8
\documentclass{article}
\usepackage{fontspec}
\setmainfont{Latin Modern Roman}
\usepackage{mwe}
\usepackage{graphics}
\gdef\getfilesize#1{%
  \directlua{
    local filename = ("\luaescapestring{#1}")
    local foundfile = kpse.find_file(filename, "tex", true)
    if foundfile then
      local size = lfs.attributes(foundfile, "size")
      if size then
        tex.write(size)
      end
    end
  }%
}
\begin{document}
\includegraphics{example-image-4x3.png}\par
Above file size: \getfilesize{example-image-4x3.png}\par
\end{document}

它報告檔案大小 1247,這是正確的。唉,我無法存取其他作業系統(Windows、Mac)。這在那裡也行得通嗎?在不同的系統上,報告的值是否相同?

編輯:我的意思是:在那些看到這個問題並使用 Windows (MiKtex) 的人中,上面的程式碼報告的數字是否與我在 Linux 上得到的數字相同?它以 PDF 形式列印。應該是一樣的,但我想確定一下。

為什麼我這樣做:圖像的使用是有限的。為了確保圖像“與之前批准的相同”而不是“由某人一路編輯”,需要進行多項檢查,例如檔案大小。

答案1

根據lfs.attributes()使用系統調用stat()它的文件對於 Linux、macOS、Windows 和 Windows 上的檔案應該會產生相同的結果透過 POSIX 標準大小是檔案的實際大小(解析符號連結後)。因此使用該方法來獲取檔案大小是安全的。如果您覺得不夠安全,可以使用 lua 中使用查找來獲取檔案大小的常見做法,請參閱我發布的其他答案。

答案2

一般情況下lfs.attributes()可以信任跨平台工作。一個較慢但保證有效的替代方案:

\documentclass{article}
\usepackage{fontspec}
\setmainfont{Latin Modern Roman}
%\usepackage{mwe}
\usepackage{graphics}
\gdef\getfilesize#1{%
  \directlua{
    function fsize (file)
      local h = io.open(file)
      local size = h:seek("end")
      assert(h:close())
      return size
    end
    local filename = ("\luaescapestring{#1}")
    local foundfile = kpse.find_file(filename, "tex", true)
    if foundfile then
      local size = fsize(foundfile)
      if size then
        tex.write(size)
      end
    end
  }%
}
\begin{document}
\includegraphics{example-image-4x3.png}\par
Above file size: \getfilesize{example-image-4x3.png}\par
\end{document}

修改自: https://www.lua.org/pil/21.3.html

相關內容