C得到文件的大小

原文地址为: C得到文件的大小

先用fopen打开文件,然后把文件指针指向文件尾.
再用ftell获得文件指针当前位置(即文件长度).

源代码:
#include "stdafx.h"
#include <stdio.h>
#include <iostream>

using namespace std;

int main()
{
FILE* fp = NULL;
int nFileLen = 0;

fp = fopen("c:/Test.txt", "rb");

if (fp == NULL)
{
cout << "can't open file" << endl;
return 0;
}

fseek(fp,0,SEEK_END); //定位到文件末
nFileLen = ftell(fp); //文件长度

cout << "file len = " << nFileLen << endl;
return 0;
}

可以用 stat (win 下 _stat)函数直接得文件尺寸。
man 2 stat

1.MFC中的方法:(C++)

CFileStatus status;
CFile::GetStatus("D:\\test.txt",status);
long lSizeOfFile;
lSizeOfFile = status.m_size;

lSizeOfFile的值就是D:\\test.txt文件的大小

2.标准C获得文件大小的5种方法
(注意:"__FILE__"指的是当前文件,你可以改为有效路径的目标文件,比如"D:\\test.txt")
struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for filesystem I/O */
blkcnt_t st_blocks; /* number of blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
}

#include "stdafx.h"
#include "stdio.h"
#include <sys/stat.h>
#include <io.h>
#include <FCNTL.H>


int getfilesize()
{
int iresult;
struct _stat buf;
iresult = _stat(__FILE__,&buf);
if(iresult == 0)
{
return buf.st_size;
}
return NULL;
}

int getfilesize01()
{
int fp;
fp=_open(__FILE__,_O_RDONLY);
if(fp==-1)
return NULL;
return _filelength(fp);
//return NULL;
}

int getfilesize02()
{
int fp;
fp=_open(__FILE__,_O_RDONLY);
if(fp==-1)
return NULL;
return _lseek(fp,0,SEEK_END);
//return NULL;
}

int getfilesize03()
{
int fp;
fp=_open(__FILE__,_O_RDONLY);
if(fp==-1)
return NULL;
return _lseek(fp,0,SEEK_END);
//return NULL;
}

int getfilesize04()
{
FILE *fp;
if((fp=fopen(__FILE__,"r"))==NULL)
return 0;
fseek(fp,0,SEEK_END);
return ftell(fp); //return NULL;
}

int getfilesize05()
{
FILE *fp;
char str[1];
if((fp=fopen(__FILE__,"rb"))==NULL)
return 0;
for(int i = 0;!feof(fp);i++)
{
fread(&str,1,1,fp);
}
return i - 1; //return NULL;
}

int main(int argc, char* argv[])
{
printf("getfilesize()=%d\n",getfilesize());
printf("getfilesize01()=%d\n",getfilesize01());
printf("getfilesize02()=%d\n",getfilesize02());
printf("getfilesize03()=%d\n",getfilesize03());
printf("getfilesize04()=%d\n",getfilesize04());
printf("getfilesize05()=%d\n",getfilesize05());
return 0;
}


转载请注明本文地址: C得到文件的大小
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值