C 的标准输入输出库 stdio 中提供了对文件进行读写的函数。
打开文件
函数签名:FILE * fopen ( const char * filename, const char * mode );
返回说明:如果成功打开该文件,则返回指向该文件的 FILE
对象的指针
参数说明:
- filename:需要打开的文件名
- mode:打开文件的模式
关于参数 mode 的取值:
值 | 说明 |
---|---|
"r" | read |
"w" | write |
"a" | append |
"r+" | read/update |
"w+" | write/update |
"a+" | append/update |
详细说明请参考:http://www.cplusplus.com/reference/cstdio/fopen/
关闭文件
函数签名:int fclose ( FILE * stream );
返回说明:如果成功关闭该文件,则返回 0
参数说明:
- stream:指向该文件的
FILE
对象的指针
详细说明请参考:http://www.cplusplus.com/reference/cstdio/fclose/
写入文件
函数签名:int fputs ( const char * str, FILE * stream );
返回说明:成功时返回非负值
参数说明:
- str:需要写入的字符串常量
- stream:指向该文件的
FILE
对象的指针
详细说明请参考:http://www.cplusplus.com/reference/cstdio/fputs/
读取文件
函数签名:char * fgets ( char * str, int num, FILE * stream );
返回说明:成功时传入的参数 str 的值
参数说明:
- str:指向在其中复制字符串读取的字符数组的指针
- num:要复制到str中的最大字符数(包括终止的空字符)
- stream:指向该文件的
FILE
对象的指针
详细说明请参考:http://www.cplusplus.com/reference/cstdio/fgets/
简单示例
#include<stdio.h>
int main() {
const char *filename = "/io.txt";
// 写
{
FILE *f = fopen("/io.txt", "w+");
int r = fputs("Hello World.\n —— marvelousness", f);
if(r > -1) {
r = fclose(f);
if(r == 0) {
// printf("写入完成.\n");
}
}
}
// 读
{
FILE *f = fopen("/io.txt", "r");
char buff[1024];
while(fgets(buff, 1024, f) != NULL) {
printf("%s", buff);
}
int r = fclose(f);
}
return 0;
}
执行结果:
Hello World.
—— marvelousness