#include <sys/stat.h>
#include <unistd.h>
const char *filePath = "/tmp/file.txt";
//要查看的文件
FILE *out = fopen(filePath, "w");
if (out != nullptr) {
fputs("Line 1\nLine 2\n", out);
fclose(out);
}
//stat 属于 POSIX:大小、权限、时间
struct stat info;
if (stat(filePath, &info) != 0) {
perror(filePath);
exit(EXIT_FAILURE);
}
//文件大小(第一种方法)
long long fileSize1 = info.st_size;
//fileSize1 is 14
//文件大小(第二种方法,标准 C)
long fileSize2 = -1;
FILE *in = fopen(filePath, "rb");
if (in != nullptr) {
fseek(in, 0, SEEK_END);
fileSize2 = ftell(in);
fclose(in);
}
//fileSize2 is 14
//文件修改时间
time_t timeChanges = info.st_mtime;
bool isFresh = difftime(time(nullptr), timeChanges) < 60;
//isFresh 为 true:文件刚刚被写入
//st_ctime 是权限最后一次变更的时间,
//不是创建时间:POSIX 不保存创建时间
//文件是否可读可写
bool isReadable = access(filePath, R_OK) == 0;
bool isWritable = access(filePath, W_OK) == 0;
//isReadable is true, isWritable is true
//文件扩展名
const char *dot = strrchr(filePath, '.');
const char *extension = dot != nullptr ? dot + 1 : "";
//extension is "txt"
//文件名和目录
const char *slash = strrchr(filePath, '/');
const char *fileName = slash != nullptr ? slash + 1 : filePath;
//fileName is "file.txt"
int dirLength = slash != nullptr ? (int)(slash - filePath) : 0;
//fileDir is "/tmp"
printf("fileSize1 is %lld\n", fileSize1);
printf("fileSize2 is %ld\n", fileSize2);
printf("isFresh is %s\n", isFresh ? "true" : "false");
printf("isReadable is %s\n", isReadable ? "true" : "false");
printf("isWritable is %s\n", isWritable ? "true" : "false");
printf("extension is %s\n", extension);
printf("fileName is %s\n", fileName);
printf("fileDir is %.*s\n", dirLength, filePath);
remove(filePath);