![](/img/trans.png)
[英]golang os *File.Readdir using lstat on all files. Can it be optimised?
[英]Getting file size using readdir
我正在調用readdir()
從目錄中獲取文件名信息。 我也只想在可能的情況下使用readdir()
打印文件大小,因為dirent
的結構是
struct dirent {
ino_t d_ino; /* inode number */
off_t d_off; /* offset to the next dirent */
unsigned short d_reclen; /* length of this record */
unsigned char d_type; /* type of file; not supported
by all file system types */
char d_name[256]; /* filename */
};
我使用d_reclen
作為文件大小,但是以某種方式我的程序打印了錯誤的值。 但是我的問題是:
d_reclen
作為文件大小是否正確? 因為我懷疑它是短無符號的,對於大文件它如何返回正確的大小。 OUTPUT
Actual Size :1bytes File size :20
Actual Size :4bytes File size :20
Actual Size :8bytes File size :20
Actual Size :256bytes File size :20
Actual Size :0bytes File size :20
Actual Size :255bytes File size :20
Actual Size :1023bytes File size :24
編輯1我正在使用printf("File size :%hu\\n",pent->d_reclen);
打印文件大小,但未給出正確答案。
編輯2由於某些性能原因,我想避免使用stat()
。
readdir
手冊說:
unsigned short d_reclen; /* length of this record */
“此記錄”是“此struct dirent
實例實例”,而不是“此文件”。
在您的情況下( d_reclne
20或24),您不應訪問整個dirent內存,因為readdir僅分配了足夠的內存來填充d_ino
, d_off
, d_reclen
, d_type
和d_name
的相關部分。 readdir
沒有為d_name
分配完整的256個字節。
要獲得文件大小,而不是文件名的大小(長度)(這是d_reclen
記錄的大小),您需要stat()
或statat()
(或lstat()
)系統調用。 您不能直接從struct dirent
的信息獲取文件大小。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.