函数接口
fputc:
man 3 fputc
原型:int fputc(int c, FILE *stream);
功能: 向stream流中写入 字符c
参数:c:要写入的字符的ASCII码值
stream:文件流指针
返回值:成功返回写入字符的ASCII码值
失败返回-1
fputc(ch, stdout) == putchar(ch)
fgetc:
man 3 fgetc
原型:int fgetc(FILE *stream);
功能:从流中接收一个字符
参数:stream:文件流指针
返回值:成功返回接收到字符的ASCII码值
失败返回EOF(-1)
读到文件末尾返回EOF(-1)
ch = fgetc(stdin) == ch = getchar(
fwrite:
man 3 fwrite
原型:size_t fwrite(const void *ptr, size_t size, size_t
nmemb,FILE *stream);
功能:向流中写入ptr指向的nmemb个元素,每个元素size字节
参数:
ptr:存放数据空间的首地址
size:每个元素的大小
nmemb:元素个数
stream:文件流指针
返回值:
成功返回写入对象的个数
失败返回0
fread:
man 3 fread
原型:size_t fread(void *ptr, size_t size, size_t nmemb, FILE
*stream);
功能:从流中读取nmemb个对象,存放ptr指向的空间中,每个对象size字节
参数:
ptr:存放数据空间首地址
size:每个元素的大小
nmemb:对象个数
stream:文件流指针
返回值:
成功返回实际读到对象个数
失败返回0
读到末尾返回
fseek:
man 3 fseek
原型:int fseek(FILE *stream, long offset, int whence);
功能:设置流的偏移量
参数:
stream:流
offset:偏移量
whence:
SEEK_SET 文件开头
SEEK_CUR 文件当前位置
SEEK_END 文件末尾
返回值:
成功返回0
失败返回-1
void rewind(FILE *stream);
功能:
将流的偏移量重新定位到开头
fseek(stream, 0, SEEK_SET) == rewind(stream)
long ftell(FILE *stream);
功能:
获得流的偏移
练习:
(1)利用fread和fwrite实现图片内容的拷贝
主函数↓↓↓↓↓↓↓
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <error.h>
int main(void)
{
FILE *pa = NULL;
FILE *pb = NULL;
char tmp[4096] = {0};
char name[32] = {0};
size_t nret = 0;
printf("输入要复制的文件名\n");
gets(name);
pa = fopen(name, "r");
if(NULL == pa)
{
ERR_MSG("打开失败");
goto err_open_pa;
}
pb = fopen("./build/b.jpg", "w");
if(NULL == pa)
{
ERR_MSG("打开失败");
goto err_open_pb;
}
while(1)
{
nret = fread(tmp, sizeof(tmp), 1, pa);
if(0 == nret)
{
break;
}
fwrite(tmp, sizeof(tmp), 1, pb);
}
printf("复制完成\n");
fclose(pa);
fclose(pb);
return 0;
err_open_pb:
fclose(pa);
err_open_pa:
return -1;
}
(2)编写程序获得一个文件中出现哪些字符?及每种字符出现的次数?及哪种字符出现的次数
最多?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <error.h>
int main(void)
{
FILE *pa = NULL;
int tmp[255] = {0};
char name[32] = {0};
char t = 0;
int i = 0;
int max = 0;
printf("输入要统计的文件名\n");
gets(name);
pa = fopen(name, "r");
if(NULL == pa)
{
ERR_MSG("打开失败");
return -1;
}
while(1)
{
t = fgetc(pa);
if(EOF == t)
{
break;
}
tmp[t]++;
}
printf("文件共出现以下字符[次数]\n");
tmp[max] = tmp[0];
for(i = 0; i < 255; i++)
{
if(tmp[i] != 0)
{
printf("字符%c 次数%d\n", i, tmp[i]);
}
if(tmp[max] < tmp[i])
{
max = i;
}
}
printf("字符\"%c\"出现的最多,%d 次\n", max, tmp[max]);
return 0;
}