fgets、fread函数
fwritre函数
文件结束函数
错误指示函数
#include
#include
int main(int arge,char **argv)
{
int ret=-1;
//拷贝 源文件(source.c)到目标文件(dst.c)
FILE *fp_s=NULL;//源文件流
fp_s=fopen("source.c","r");//只读该文件 r
if(NULL==fp_s)
{
perror("fopen source.c");
return -1;
}
//目的文件
FILE *fp_d=NULL;//目标文件流
fp_d=fopen("dst.c","w");
if(fp_d==NULL)
{
perror("fopen dst.c");
return -1;
}
//准备内存
char *buff=NULL;
buff=malloc(20);//堆 20个字节
if(NULL==buff){
perror("malloc buff");
return -1;
}
//读
//文件,内存地址,读多少内容
//给读函数提供的信息:读的文件的名称,读到那去,读多少,从哪里开始读。
//从源文件的默认光标(文件位置处)
//存放到用户内存里面
while(1)
{
ret= fread(buff,1,20,fp_s);
if(20>ret)
{
//读到source.c文件的尾部
if(feof(fp_s))
{
ret=fwrite(buff,1,ret,fp_d);
if(0==ret)
{
perror("fwrite");
return -1;
}
break;
}else{
//出错
perror("fread");
return -1;
}
}
//写
ret=fwrite(buff,1,ret,fp_d);
if(0==ret){
perror("fwrite");
return -1;
}
}
free(buff);
buff=NULL;
fclose(fp_d);
fp_d=NULL;
fclose(fp_s);
fp_s=NULL;
return 1;
}
详解这个函数的返回值:
RETURN VALUE
fread() and fwrite()
return the number of items successfully read or written (i.e., not the number of characters).
If an error occurs, or the end-of-file is reached, the return value is ashort item count (or zero).
如果成功返回就是item,如果错误返回就是short item,如果end-of-file就返回zero。
The function feof()
tests the end-of-file indicator for the stream pointed to by stream, returning non-zero if it is set. The end-of-file indicator can only be cleared by the function clear- err().
The function ferror()
tests the error indicator for the stream pointed to by stream, returning non-zero if it is set. The error indicator can only be reset by the clearerr() function.
fread函数的返回值就三种:item,short item,zero。不是item这种情况,就是short item和zero这两种情况,
ret= fread(buff,1,20,fp_s);
if(20>ret)
{
//读到source.c文件的尾部
if(feof(fp_s))
{
ret=fwrite(buff,1,ret,fp_d);
if(0==ret)
{
perror("fwrite");
return -1;
}
break;
}else{
//出错
perror("fread");
return -1;
}
}
执行程序:
gcc mycopy.c -g
./a.out
gdb a.out
b main(在main函数处设置断点)
r运行
n
n
p fp_s(显示)
p fp_d
s
p buff
总结:
第一步:打开文件(fopen)
FILE *fp_s=NULL;//源文件流 fp_s=fopen("source.c","r");//只读该文件 r
第二步:准备内存空间
buff=malloc(20);//堆 20个字节
第三步:
进行读写操作。
ret=fwrite(buff,1,ret,fp_d);
ret= fread(buff,1,20,fp_s);
第四步:关闭数据流,释放内存
第一是:逻辑思维(有计算机执行决定)
第二是:需要用到的函数(熟悉函数的用法)