linux下c语言编程lstat
时间: 2023-11-17 09:05:31 浏览: 176
在Linux下使用C语言编程,可以使用lstat函数获取文件的状态信息,其原型为:
```c
int lstat(const char *pathname, struct stat *statbuf);
```
其中,pathname参数为要获取状态信息的文件路径,statbuf参数为存储获取到的状态信息的结构体指针。
示例代码如下:
```c
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
struct stat sb;
if (argc != 2) {
fprintf(stderr, "Usage: %s <pathname>\n", argv[0]);
return 1;
}
if (lstat(argv[1], &sb) == -1) {
perror("lstat");
return 1;
}
printf("File type: ");
switch (sb.st_mode & S_IFMT) {
case S_IFBLK:
printf("block device\n");
break;
case S_IFCHR:
printf("character device\n");
break;
case S_IFDIR:
printf("directory\n");
break;
case S_IFIFO:
printf("FIFO/pipe\n");
break;
case S_IFLNK:
printf("symlink\n");
break;
case S_IFREG:
printf("regular file\n");
break;
case S_IFSOCK:
printf("socket\n");
break;
default:
printf("unknown?\n");
break;
}
printf("I-node number: %ld\n", (long)sb.st_ino);
printf("Mode: %lo (octal)\n", (unsigned long)sb.st_mode);
printf("Link count: %ld\n", (long)sb.st_nlink);
printf("Ownership: UID=%ld GID=%ld\n", (long)sb.st_uid, (long)sb.st_gid);
printf("Preferred I/O block size: %ld bytes\n", (long)sb.st_blksize);
printf("File size: %lld bytes\n", (long long)sb.st_size);
printf("Blocks allocated: %lld\n", (long long)sb.st_blocks);
printf("Last status change: %s", ctime(&sb.st_ctime));
printf("Last file access: %s", ctime(&sb.st_atime));
printf("Last file modification: %s", ctime(&sb.st_mtime));
return 0;
}
```
该示例代码可以获取指定文件的状态信息,并输出到终端上。注意,在使用ctime函数输出时间时,需要将时间戳传入该函数,以获取可读性较好的时间格式。
阅读全文