问题:
在C语言中需要查询系统中指定文件的大小,在命令行中可以使用的方法很多:
ls -l ./a.txt
du -b ./a.txt但C语言如果调用命令获取命令结果,需要以popen(char* command, char* buf)来取得结果,比较不方便,经一番搜寻,发现C语言本身的函数就可以解决这一问题。
解决办法:
1. 使用stat()编写自定义的函数get_file_size();
static int get_file_size(const char* file) {
struct stat tbuf;
stat(file, &tbuf);
return tbuf.st_size;
}
使用示例:
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
static int get_file_size(const char* file) {
struct stat tbuf;
stat(file, &tbuf);
return tbuf.st_size;
}
int main() {
struct stat buf;
stat("./test.log", &buf);
printf("test.log file size = %d \n", (int)buf.st_size);
printf("test.log file size is: %d \n", get_file_size("./test.log"));
return 0;
}
编译:
hxtc@hxtc-pd:~/work/debug/c_debug/src/c_exer$ gcc -std=gnu99 -o test_stat test_stat.c运行结果:
hxtc@hxtc-pd:~/work/debug/c_debug/src/c_exer$ ./test_stat
test.log file size = 8358940
test.log file size is: 8358940

本文介绍了一种在C语言中查询文件大小的有效方法,通过使用系统自带的stat()函数,无需借助外部命令即可轻松实现。文章提供了完整的示例代码。

被折叠的 条评论
为什么被折叠?



