liunx cc++怎么判断是否是否普通文件怎么获取文件大小。给出实现代码
在Linux下,可以使用stat()函数来判断文件是否为普通文件,并使用st_size成员变量来获取文件大小。
以下是一个示例代码:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
struct stat st;
const char* filename = "example.txt";
if (stat(filename, &st) == 0) {
if (S_ISREG(st.st_mode)) {
printf("%s 是普通文件\n", filename);
printf("文件大小为 %ld 字节\n", st.st_size);
} else {
printf("%s 不是普通文件\n", filename);
}
} else {
perror("获取文件信息失败");
}
return 0;
}
请确保文件存在并有读权限,替换example.txt为你要判断的文件路径
原文地址: https://www.cveoy.top/t/topic/iqho 著作权归作者所有。请勿转载和采集!