一、函数接口
1、fwrite:

2、fread:

二、流的定位
1、概念
设置流的偏移量
2、偏移量的设置
1)fseek

2、ftell

3、rewind

三、标准IO函数接口练习
1、题目:计算文件文本的行数
代码实现
#include <stdio.h>
int main(void)
{
FILE *fp = NULL;
char ch = 0;
char str[256] = {0};
int cnt = 1; //cnt要从1开始,因为行数是从1开始的printf("请输入文件名:\n");
gets(str);fp = fopen(str,"r");
if (NULL == fp)
{
perror("fail to fopen");
return -1;}
while (1)
{
ch = fgetc(fp);
if (EOF == ch)
{
break;
}
if ('\n' == ch)
{
cnt++;
}
}
printf("共有%d行\n",cnt);
fclose(fp);return 0;
}
2、题目:利用fgetc、fputc实现文件拷贝
#include <stdio.h>
int main(void)
{
FILE *fp1 = NULL;
FILE *fp2 = NULL;
char ch = 0;fp1 = fopen("a.txt","r");
if (NULL == fp1)
{
perror("fail to open-fp1");
return -1;
}
fp2 = fopen("b.txt","w");
if (NULL == fp2)
{
perror("fail to open-fp2");
return -1;
}while (1)
{
ch = fgetc(fp1);
if (EOF == ch)
{
break;
}
fputc(ch,fp2);
}fclose(fp1);
fclose(fp2);
return 0;
}
3、题目:从终端输入一个文件名,获得文件的长度
#include <stdio.h>
int main(void)
{
FILE *fp = NULL;
long len = 0;fp = fopen("a.txt","r");
if (NULL == fp)
{
perror("fail to fopen");
return -1;
}fseek(fp,0,SEEK_END);
len = ftell(fp);
printf("len = %ld\n",len);fclose(fp);
return 0;
}
4、题目:从bmp文件中读取图片的宽度和高度
#include <stdio.h>
int main(void)
{
FILE *fp = NULL;
int width = 0;
int height = 0;fp = fopen("1.bmp","r");
if (NULL == fp)
{
perror("fail to fopen");
return -1;
}
fseek(fp,18,SEEK_CUR);fread(&width,sizeof(width),1,fp); //中转站可以是一个int型
printf("width=%d\n",width);fread(&height,sizeof(height),1,fp);
printf("heigth=%d\n",height);
fclose(fp);
return 0;
}
5、题目:利用fread、fwrite实现拷贝图片
#include <stdio.h>
int main(void)
{
FILE *fp = NULL;
FILE *fp2 = NULL;
char tmpbuff[4096] = {0};
size_t nret = 0;fp = fopen("fd.JPG","r");
if (NULL == fp)
{
perror("fail to fopen");
return -1;
}
fp2 = fopen("fd2.png","w");
if (NULL == fp2)
{
perror("fail to fopen");
return -1;
}while (1)
{
nret = fread(&tmpbuff,1,sizeof(tmpbuff),fp);
if (0 == nret)
{
break;
}
fwrite(&tmpbuff,1,nret,fp2);
}#if 0 //此处写法容易丢失少部分的末尾数据
while(1)
{
nret = fread(&tmpbuff,sizeof(tmpbuff),1,fp);
if (0 == nret)
{
break;
}
fwrite(&tmpbuff,sizeof(tmpbuff),1,fp2);
}
#endiffclose(fp);
fclose(fp2);return 0;
}

被折叠的 条评论
为什么被折叠?



