C语言-第十三章文件操作

文件操作
程序启动时 从文件中加载数据到程序中
程序退出前 把程序中处理的数据保存到文件
C语言提供用于文件操作的函数:

FILE *fopen(const char *path,const char *mode);
	path: 文件路径   包含文件名
		绝对路径    "/home/ubuntu/a.txt"
		相对路径    "a.txt" 
	mode: 打开方式
		"r"    read   只读
		"w"    write  只写
		"a"    append 追加

FILE * 文件指针 结构体指针
如果fopen失败 返回 NULL
如果成功则返回可以用于文件操作的文件指针

   r    Open  text  file  for  reading.  The stream is positioned at the
          beginning of the file.
		  打开文件用于读,从文件开始位置读
		  只要文件不存在,失败

   r+   Open for reading and writing.  The stream is positioned  at  the
          beginning of the file.
		  打开文件用于读和写  从文件开始位置读和写
		  只要文件不存在,失败

   w      Truncate  file  to  zero length or create text file for writing.
          The stream is positioned at the beginning of the file.
		  打开文件用于写  如果文件不存在则创建  文件存在则清空
		  从文件最开始位置开始写

   w+     Open for reading and writing.  The file is created  if  it  does
          not  exist, otherwise it is truncated.  The stream is positioned
          at the beginning of the file.
		  打开文件用于读和写 
		  如果文件不存在则创建  文件存在则清空(截断)
		  从文件开始位置读写
		  
   a      Open for appending (writing at end of file).  The file  is  cre‐
          ated  if it does not exist.  The stream is positioned at the end
          of the file.
		  打开文件用于追加写
		  如果文件存在则打开在末尾追加写   文件不存在则创建	  

   a+     Open for reading and appending (writing at end  of  file).   The
          file is created if it does not exist.  The initial file position
          for reading is at the beginning  of  the  file,  but  output  is
          always appended to the end of the file.
		  打开文件用于读和追加写
		  文件不存在则创建
			如果是用于读是从开始位置读  写是在文件末尾写
			一旦读写之后,读写位置会合并
	组合模式:		
	"rw"
	"r+w"
	"b"  以二进制的方式进行读写
	"t"  以文件方式进行读写
	
	
int fclose(FILE* fp);

ssize_t fread(void *ptr,size_t size,size_t nmemb,FILE *stream);
	期望读取nmemb个size字节大小的数据到ptr中去
	返回成功读取的次数
ssize_t fwrite(const void *ptr,size_t size,size_t nmemb,FILE *stream);
	返回成功读写的次数 (不是字节数)
	如果在某个位置开始文件中有内容,但是在这个位置写入会覆盖

int fseek(FILE *stream,long offse,int whence);//设置文件读写位置
	long offset : 偏移多少个字节  可正可负
	int  whence : 参考位置
		SEEK_SET   :文件开始位置
		SEEK_CUR   :当前位置
		SEEK_END   :文件末尾位置

long ftell(FILE *stream); //获取文件读写位置(偏移文件开始位置的长度字节)
void rewind(FILE *stream);//把读写文件设置到文件开始位置

//格式输入输出的效率要低
int fscanf(FILE *stream,const char *format,...);
int printf(FILE *stream,const char *format,...);

int feof(FILE *stream); 用于判断是否已经到达文件末尾   
	一定是到达文件最后位置的后面才返回1    EOF  代表文件末尾位置
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值