fopen() 函数:
FILE *fopen(const char *filename, const char *mode)
https://www.runoob.com/cprogramming/c-function-fopen.html
fseek() 函数:
int fseek(FILE *stream, long int offset, int whence)
https://www.runoob.com/cprogramming/c-function-fseek.html
ftell() 函数:
long int ftell(FILE *stream)
https://www.runoob.com/cprogramming/c-function-ftell.html
fread() 函数:
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream)
https://www.runoob.com/cprogramming/c-function-fread.html
fwrite() 函数:
size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
https://www.runoob.com/cprogramming/c-function-fwrite.html
fclose() 函数:
int fclose(FILE *stream)
https://www.runoob.com/cprogramming/c-function-fclose.html
C 标准库 - <stdio.h>
https://www.runoob.com/cprogramming/c-standard-library-stdio-h.html
获取文件大小:
#include <stdio.h>
int main ()
{
FILE *fp;
int len;
char str[] = "This is runoob.com";
fp = fopen( "file.txt" , "w" );
fwrite(str, sizeof(str) , 1, fp );//注意sizeof(str)是19个字节
fclose(fp);
fp = fopen("file.txt", "r"); //前提该文件必须存在
if( fp == NULL )
{
perror ("打开文件错误");
return(-1);
}
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fclose(fp);
printf("file.txt 的总大小 = %d 字节\n", len);
return(0);
}
读取文件内容:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main ()
{
FILE *fp;
int len;
char *pbuf = NULL;
char str[] = "This is runoob.com";
fp = fopen( "file.txt" , "w" );
fwrite(str, sizeof(str) , 1, fp );//注意sizeof(str)是19个字节
fclose(fp);
fp = fopen("file.txt", "r"); //前提该文件必须存在
if( fp == NULL )
{
perror ("打开文件错误");
return(-1);
}
fseek(fp, 0, SEEK_END);
len = ftell(fp);
fseek(fp, 0, SEEK_SET);
//申请内存
pbuf= (char *) malloc(len+1);
memset(pbuf,0,len+1);
/* 读取并显示数据 */
fread(pbuf, len, 1, fp);
printf("show: %s.\n", pbuf);
fclose(fp);
printf("file.txt 的总大小 = %d 字节\n", len);
return(0);
}