您的位置:首页 > 编程语言 > C语言/C++

C语言中的文件输入、输出(file I/O)

2013-04-05 13:27 169 查看
0.
目录

1. 打开、关闭、定位
2. 无格式输入、输出
3. 格式化输入、输出
4. 按行输入、输出
5. 单字符输入、输出
6. 错误检测函数

1. 打开、关闭、定位
Open a file: fopen
FILE *fopen(const char *path,const char *mode);
return NULL if failed.
++++++++++++++++++++++++++++++++++++++++++++++++++
Mode Description
==================================================
r rb read only
w wb write only(overrideif file exists)
a ab append
r+ rb+ read & write
w+ wb+ read & write(override the file)
a+ ab+ read & write(append if file exests)
++++++++++++++++++++++++++++++++++++++++++++++++++
The 'b' stands for binary.

Close a file: fclose
int fclose(FILE *fp);
return 0 if success, EOF otherwise.

Seek to a special position: fseek, ftell
int fseek(FILE *stream, long offset, int whence);
return 0 if success
long ftell(FILE *stream);
return offset of the stream.
+++++++++++++++++++++++++++++++++
whence Discription
=================================
SEEK_SET(0) start ofthe file
SEEK_CUR(1) current position
SEEK_END(2) end of thefile
+++++++++++++++++++++++++++++++++
2. 无格式输入、输出
Input from a file without any format:fread
size_t fread(void *ptr, size_t size, size_t nmemb, FILE*stream);
Output to a file without any format:fwrite
size_t fwrite(const void *ptr, size_t size, size_tnmemb,FILE *stream);
返回实际读取或写入的字符/字节数目,error or EOF时函数结束。

3. 格式化输入、输出
Input from a file with format: fscanf
int fscanf(FILE *stream, const char *format, ...);
Output to a file with format: fprintf
int fprintf(FILE *stream, const char *format, ...);
返回实际读取或写入的字符/字节数目,error or EOF时函数结束。
FORMAT is important!
4. 按行输入、输出
从文件中读取一行: fgets
char *fgets(char *s, int size, FILE*stream);
读取不超过size个字符,遇到EOL or EOF结束; 成功,返回指针(即s),否则返回NULL 换行符也被读入,并且结果字符串结尾自动添加'\0'
将字符串按行写入文件: fputs
int fputs(const char *s, FILE *stream);
将字符串s写入文件,不包含结尾的'\0'。返回实际写入的字符数。 注意:不是按行写入,而是完全写入。
5. 单字符输入、输出
一次读入一个字符: fgetc
int fgetc(FILE *stream);
返回:将读入字符视作unsigned char形式并转换为int时的值
一次写出一个字符: fputc
int fputc(int c, FILE *stream);
返回:将写出字符视作unsigned char形式并转换为int时的值

6. 错误检测函数
检测是否到达文件结尾: feof
int feof(FILE *stream);
到达文件结尾:返回非零
检测文件错误: ferror
int ferror(FILE *stream);
文件出错:返回非零
返回文件描述符: fileno
int fileno(FILE *stream);
返回文件描述符的整数值

P.S. 校内果然不是发布blog的地方,挺漂亮的格式搞得乱七八糟,而且即使手动也毫无排版的可能。
P.S. 这里只是列举出一部分文件I/O函数,还是很多其他的,例如read/write。正因为其多且杂才稍作整理,只需记忆一个大概轮廓,用到时在查看manual吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: