标准 io 篇
1. fopen 文件打开
函数原形
#include <stdio.h>
FILE *fopen(const char *path, const char *mode);
// const char* 保护实参不被修改
参数
-
path 文件名(包含路径:绝对路径或者相对路径)
-
mode 文件打开的方式
-
r 以只读方式打开 文件必须已存在
-
r+ 以读写方式打开 文件必须已存在
-
w 以只写方式打开 如果不存在 则创建并打开 存在则清空并打开
-
w+ 以读写方式打开 如果不存在 则创建并打开 存在则清空并打开
-
a 以追加写的方式打开 如果文件不存在 则创建并打开
-
a+ 以追加读写的方式打开 如果文件不存在 则创建并打开
-
返回值 成功返回FILE* 类型指针(文件流指针) 失败返回NULL
示例程序
#include<stdio.h>
#include<stdlib.h>//exit头文件
int main()
{
FILE * fp=NULL;
//只写的方式打开文件
fp = fopen("first.txt","w");//调用
if(NULL==fp)//#define NULL (void *)0
{
printf("文件打开失败\n");
exit(-1);//退出整个程序
}
return 0;
}
tips
程序运行时 系统自动打开3个流
描述 | 类型 | 含义 |
---|---|---|
stdin | FILE * stdin | 从标准输入取数据,默认是键盘 |
stdout | FILE * stdout | 向标准输出设备输出,默认是显示器 |
stderr | FILE * stderr | 向标准错误输出设备输出,默认是显示器 |
2. fclose 关闭文件
函数原型
#include <stdio.h>
int fclose(FILE *fp);// fclose(fp);
//功能:关闭文件
3. perror 错误提示
函数原型
#include <stdio.h>
void perror(const char *s);
//功能:返回上一个函数的错误信息
//参数:实际错误信息
4. fgets 按行读取
函数原型
#include<stdio.h>
char *fgets(char *s, int size, FILE *stream);
//功能:从文件中读取一行
参数
-
s: 读取的数据存放的位置
-
size: 最多读多大 实际最多能读到的有效字符 size-1个字节
-
stream: 从stream文件中读取一行
-
返回值: 成功 返回读到的数据 ,失败或者到文件结尾 返回NULL
备注
如果size < 行字节数,实际读取有效字符size - 1,剩下的字符需要循环读取 直到 ’\n’。
如果size > 行字节数,实际读到一行。(遇到 ’\n’ 停止)
6. fputs 向文件中写入一行数据
函数原型
#include<stdio.h>
int fputs(const char *s, FILE *stream);
//功能:向文件中写入一行
参数
- s: 存放要写入文件的字符串
- stream: 要写入的文件
- 返回值: 成功:返回非负数。 失败:返回EOF //EOF是文件结束标志
示例程序
//存在文件 stu.txt (有内容),读取stu.txt内容,并将读到的内容写入note.txt
#include<stdio.h>
#include<stdlib.h>
#include<strings.h>
//./mycp first.txt note.txt
int main(int argc,char *argv[])
{
//argc!=3 错误处理
if(argc!=3)
{
printf("%s 源文件名 目标文件名\n",argv[0]);
exit(-1);
}
char buf[100]="\0";
char *pret = NULL;
//1.打开源文件 fpSrc argv[1] "r"
FILE *fpSrc = fopen(argv[1],"r");
if(NULL==fpSrc)
{
perror("fopenSrc");
exit(-1);
}
//2.打开目标文件 fpDst argv[2] "w"
FILE * fpDst = fopen(argv[2],"w");
if(NULL==fpDst)
{
perror("fopenDst"<