fgets函数
(1)功能:每次读取一行
(2)头文件及函数原型
#include <stdio.h>
char *fgets(char *s, int size, FILE *stream);
(3)参数说明:
char buf[100]; //用来保存读取出的一行字符串
fgets(buf, 100, fp); //调用一次,读取一行字符串,保存到buf数组中
char *s //读出的一行字符串存储的位置
int size //最多能够读取的字符数
FILE *stream //流,就fopen的返回值,流和打开的文件关联在一起
(4)返回值:
成功:char * 返回值指向读取出字符串的首地址
失败:返回 NULL ,读取到文件尾返回NULL
fgetc函数,读取到文件的尾巴返回值是 EOF(-1)
fgets函数,读取到文件的尾巴返回值是 NULL
(5) 实例
char buf[100]; //用来保存读取的一行
fgets(buf, 100, fp);
fputs函数
(1)功能: 每次写入一行
(2)头文件及函数原型
#include <stdio.h>
int fputs(const char *s, FILE *stream);
(3)参数说明:
char buf[100] = "hello world!!!";
fputs(buf, fp);
const char *s //即将写入文件中的字符串,存放的位置
FILE *stream //流 ---> 关联打开的文件 fopen函数的返回值
(4)返回值:
成功:>= 0
失败:返回 EOF
(5)实例:
char buf[100] = "hello world";
fputs(buf,fp);
下面利用fgets函数与fputs函数实现文件内容拷贝
#include <stdio.h>
int main(int argc, const char *argv[])
{
if(argc != 3)
{
printf("忘记传递参数了!! ./a.out a.c b.c \n");
return -1;
}
char buf[100];//用来保存每次读取的内容
//打开两个文件
FILE* fpr = fopen(argv[1], "r");
FILE* fpw = fopen(argv[2], "w");
if(fpr == NULL || fpw == NULL)
{
printf("fopen failed!!\n");
return -1;
}
//循环拷贝,从a.c中每读取出一行字符串,就立刻写入另一个文件b.c中
while(fgets(buf, 100, fpr) != NULL)//读取内容到buf
fputs(buf, fpw);//再将读取的buf写入另一个文件
//关闭文件
fclose(fpr);
fclose(fpw);
return 0;
}