fopen等文件读写函数

博客介绍了C语言中多个文件操作函数,如fopen()、fseek()、ftell()等,还给出了各函数的参考链接,以及C标准库<stdio.h>的链接,同时提及获取文件大小和读取文件内容相关内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值