版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/88777502
一 获取文件的大小
1 代码
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
int main() {
struct stat buf;
stat("/etc/hosts", &buf);
printf("/etc/hosts file size = %d\n", buf.st_size);
stat("test.cpp", &buf);
printf("test.cpp size = %d\n", buf.st_size);
}
2 运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
/etc/hosts file size = 158
test.cpp size = 258
[root@localhost test]# ll test.cpp
-rw-r--r--. 1 root root 258 Mar 24 15:32 test.cpp
[root@localhost test]# ll /etc/hosts
-rw-r--r--. 1 root root 158 Jun 7 2013 /etc/hosts
二 判断文件是否存在
1 代码
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>//for ENOENT
#include <string.h>//for memset
int main()
{
struct stat st;
memset(&st, 0, sizeof(st));
if (!stat("test.cpp", &st)) //如果myfil.txt不存在,stat就会返回非0
{
if (st.st_size >= 0) //加了一层保证
{
printf("test.cpp exists.\n");
}
}
else if(ENOENT == errno)
printf("test.cpp does NOT exist:%d\n",errno);
}
2 运行
[root@localhost test]# g++ test.cpp -o test
[root@localhost test]# ./test
test.cpp exists.