Linux c 获取文件大小两种方式
Linux c 获取文件大小两种方式Linux c 获取文件大小(1)Linux c 获取文件大小(2)测试Linux c 获取文件大小(1)/*需要头文件#include <stdarg.h>*/int getFileSize1(const char *fileName){FILE *fp = NULL;int fileSize = 0;...
·
Linux c 获取文件大小两种方式
1. Linux c 获取文件大小(1)
/*
需要头文件
#include <stdarg.h>
*/
int getFileSize1(const char *fileName)
{
FILE *fp = NULL;
int fileSize = 0;
fp = fopen(fileName , "r");
if(NULL == fp)
{
return 0;
}
/*
1. int fseek(FILE *stream, long int offset, int whence)
功能: 设置流 stream 的文件位置为给定的偏移 offset,
参数 offset 意味着从给定的 whence 位置查找的字节数。
参数:offset 相对 whence 的偏移量,以字节为单位
whence :起始位置(从这开始偏移)
SEEK_SET:0,文件开头;
SEEK_END:2,文件末尾;
SEEK_CUR:1,文件指针当前位置
3. ftell 用于得到文件位置指针当前位置相对于文件首的偏移字节数
*/
fseek(fp, 0L, SEEK_END);
fileSize = ftell(fp);
(void)fclode(fp);
return fileSize;
}
2. Linux c 获取文件大小(2)
/*
需要头文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
*/
int getFileSize2(const char *fileName)
{
int fileSize = 0;
struct stat stFile;
int iFileFd = 0;
iFileFd = open(fileName, O_RDONLY);
if(iFileFd < 0)
{
return 0;
}
/*
说明:
1. struct stat,这是一个保存文件状态信息的结构体
2. stat中的 st_mode; //文件对应的模式,文件,目录等
3. S_ISREG判断文件是否是一个常规文件
4. 常用: S_ISDIR 判断是否是一个目录
*/
if( (0 == fstat(iFileFd, &stFile)) && S_ISREG(stFile.st_mode) )
{
fileSize = (int)stFile.st_size;
}
/*
//或者简单处理
fstat(iFiledFd, &stFile);
fileSize = stFile.st_size;
*/
return fileSize ;
}
3. 测试
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define BUF_LEN 1024
void test()
{
char buf[BUF_LEN];
int fileSize = 0;
memset(buf, 0, sizeof(buf));
getcwd(buf,BUF_LEN); //获取当前路径
strcat(buf, "/abc.txt"); //测试当前路径下abc.txt 文件大小
fileSize = getFileSize1(buf);
fileSize = getFileSize2(buf);
}
参考
更多推荐
已为社区贡献4条内容
所有评论(0)