[C] C file operate
2018-03-21 22:22
155 查看
c语言中的文件操作
c语言处理文件的两种方式–文本视图和二进制视图标准文件:c语言自动为我们打开了三个文件,这三个文件是标准输入、标准输出、标准出错。
1.如何打开和关闭一个文件
FILE *fp=NULL; fp=fopen("/home/jack/hello.c","r"); fclose(fp);
打开方式有很多种,还可以二进制打开”rb”。此处不一一列举。
2.读写文本文件与二进制文件
FILE *fp=NULL;
fp 是一个文件指针。其指向了打开的文件。一起文件的操作皆通过文件指针fp完成。当通过getc读取一个文件时,文件指针会自动+1,指向下一个字节。putc也同理。
例如,可以通过fp进行内容的读写。
2.1getc与fgetc读取文件
getc(fp); fgetc(buf,MAX,fp);
#include <stdio.h> int main() { FILE *fp; fp = fopen("hello", "r"); char ch; while ((ch=getc(fp))!=EOF){ putchar(ch); } fclose(fp); }
2.2putc与fputc写入文件
putc(fp); fputc(buf,fp);
#include <stdio.h> #include <string.h> int main() { FILE *fp; fp = fopen("hello", "w"); char *s = "hello world..."; int len = strlen(s); for (int i = 0; i < len; i++) { putc(s[i], fp); } fclose(fp); }
3.二进制I/O-fread与fwrite
fread(buffer,255,1,fp);//读取一个255字节的buffer fwrite(buffer,sizeof(double),10,fp);//写入10个double
4.操作文件指针
fseek设置文件指针的位置fseek(fp,number,SEEK_END);//结尾+number fseek(fp,number,SEEK_SET);//开始+number fseek(fp,number,SEEK_CUR);//当前位置+number
ftell获取文件指针的位置
int index; index=ftell(fp);
5.fprintf,fscanf从指定流读取内容
#include <stdio.h> #include <malloc.h> int main() { char *string = (char *) malloc(20); fscanf(stdin, "%s", string); fprintf(stdout, "%s", string); }
6.feof与ferror–检测是否到达文件结尾
当标准输入函数返回EOF时,通常已经表示到达文件结尾。但是这也有可能表示读取发生了错误。如何判断时哪种情况呢?feof与ferror可以帮助我们判断。feof(fp); ferror(fp);
当到达文件结尾时,feof(fp)返回非零值,否则返回0;当出错时,ferror(fp)返回0,否则返回非零值。
相关文章推荐
- Can LotusScript operate on Private Views?
- How to: Configure WCF Service to Interoperate with ASP.NET Web Service Clients
- ModalPopupExtender使用技巧( operate ModalPopupExtender by JavaScript)
- how to operate BHO(browser help object)
- 常用的DBOperate之九——返回数据库连接的静态方法
- how to operate softmac
- English_operate/feasible
- C# FileOperateHelper文件操作类与源码下载
- Multiple address space mapping technique for shared memory wherein a processor operates a fault handling routine upon a translator miss
- Assembly x64 Intro - Floating Point Operate
- (hibernate)You can't operate on a closed ResultSet
- I reinstall the Operate System today!
- 全能的数据库系统开发类BaseOperate.cs
- Instructing the GSM/GPRS Modem or Mobile Phone to Operate in SMS Text Mode
- jquery option operate
- Effective c++学习笔记——条款11:在operateor=中自我赋值
- C++ FILE OPERATE
- The operate of stack
- C# - Operator &, | and ^ can also operate bool operands
- create table repo_folder_operate_log_bak as select * from repo_folder_operate_log;