C语言获取文件大小和生成空洞文件

获取文件大小

1.通过fgetc函数
#include<stdio.h>
#include<stdlib.h>

int main(){
    FILE * fp = fopen("text","r");
    int ch;
    int size = 0;
    while ((ch = fgetc(fp)) != EOF)
    {
        size++;
    }
    printf("文件大小:%d\n",size);
    return 0;
}
2.通过fseek与ftell函数
#include<stdio.h>
#include<stdlib.h>

int main(){
    FILE * fp = fopen("text","r");
    fseek(fp,0,SEEK_END);
    int size = ftell(fp);
    printf("文件大小:%d\n",size);
    return 0;
}
3.通过stat函数
#include<stdio.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(){
    FILE * fp = fopen("text","r");
    int fd = open("text",O_RDONLY);
    struct stat file_properties;
    fstat(fd,&file_properties);
    off_t size = file_properties.st_size;
    printf("文件大小:%ld\n",size);
    return 0;
}

以上几个方法执行的效果都如下:



读取的text文件如下:

sadasda
asdasdasd
asdafdgdfsdf
dfsdfadsfas

生成空洞文件

空洞文件即是里面内容都是空字符的文件,主要用来占位置,实现如下:

#include<stdio.h>
#include<stdlib.h>

int main(){

    FILE * fp = fopen("test","w+");
    //将文件位置往后移1023个字节
    fseek(fp,1023L,SEEK_SET);
    //往末尾写一个空字符这样就是1024个字节了,要不生成的文件就是空了
    fwrite("",1,1,fp);
    fclose(fp);
    return 0;
}

生成的文件如下:



用vim打开是这样的


©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 方法一: 获得文件大小需要用到2个函数:fseek() , ftell() fseek()函数: 原型:intfs...
    月震阅读 4,533评论 0 0
  • 在优化Http文件服务器时,遇到了一些疑惑,就是怎么获取一个文件的大小?目前我知道有两种方式,分别是: 通过sta...
    夏楚子悦阅读 1,339评论 0 1
  • 第三章 文件i/o 3.1引言 不带缓冲的io(unix系统在内核中设有缓冲区,这个不带缓冲意思是用户不自己缓冲)...
    m风满楼阅读 1,023评论 0 0
  • 文件操作 (Linux文件操作)) [文件|目录] Linux文件操作:为了对文件和目录进程处理,你需要用到系统...
    JamesPeng阅读 1,501评论 1 5
  • 一、概述 标准IO:标准I/O是ANSI C建立的一个标准I/O模型,是一个标准函数包和stdio.h头文件中的定...
    梁帆阅读 1,886评论 0 1