C++获取文件的有关信息

一 获取文件的大小

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.

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值