Linux下获取文件大小(程序)

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <error.h>
 5 #include <sys/types.h>
 6 #include <sys/stat.h>
 7 #include <unistd.h>
 8 
 9 /*
10 Linux终端输入提示符下输入命令:man 2 stat
11 
12 stat, fstat, lstat - get file status
13 
14 有点类似于exec函数族一样的,stat函数族。
15 
16 int stat(const char* path, struct stat* buf);
17 int fstat(int fd, struct stat* buf);
18 int lstat(const char* path, struct stat* buf);
19 
20 struct stat {
21     dev_t     st_dev;     // ID of device containing file
22     ino_t     st_ino;     // inode number
23     mode_t    st_mode;    // protection
24     nlink_t   st_nlink;   // number of hard links
25     uid_t     st_uid;     // user ID of owner
26     gid_t     st_gid;     // group ID of owner
27     dev_t     st_rdev;    // device ID (if special file)
28     off_t     st_size;    // total size, in bytes
29     blksize_t st_blksize; // blocksize for file system I/O
30     blkcnt_t  st_blocks;  // number of 512B blocks allocated
31     time_t    st_atime;   // time of last access
32     time_t    st_mtime;   // time of last modification
33     time_t    st_ctime;   // time of last status change
34 };
35 */
36 
37 int main(int arc, char* const argv[])
38 {
39     struct stat fileInfo;
40     if (stat("main.c", &fileInfo) == 0)
41         printf("The file size: %d byte!\n", fileInfo.st_size);
42 
43     return 0;
44 }

总结:发现这个程序去掉#include <unistd.h>,也可以在Windows下运行。

仔细一查,Winows也有sys/types.h和sys/stat.h文件,struct stat的定义也差不多。

额,有点惊喜,Windows也遵循POSIX标准哈!

原文地址:https://www.cnblogs.com/Robotke1/p/3038277.html