您的位置:首页 > 编程语言 > C语言/C++

C语言中获取文件大小的函数

2014-05-14 20:21 351 查看

问题:

在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




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: