getc(),putc()文件文本读取写入函数

来源:互联网 发布:体育数据分析公司 编辑:程序博客网 时间:2024/06/05 16:48

getc()和putc的基本用法:
原型:getc(FILE _*File); 接受一个指针
putc(int _ch,FILE _*File); 接受两个参数,1.整数型数据 2.文件指针,包含(stdout,stderr)
文件读取示例:

#include<stdio.h>#include<stdlib.h>int main(void){    FILE *pi;    int k;    if((pi=fopen("file","r"))==NULL){        puts("Open file error!");        exit(EXIT_FAILURE);}    while((k=getc(pi))!=EOF)        putc(k,stdout);    if(fclose(pi)!=0)        puts("Close file error!");    return 0;}

文件压缩程序示例:

#include<stdio.h>#include<string.h>#include<stdlib.h>#define SIZE 40int main(void){    FILE *hi,*hl;    char name[SIZE],file[SIZE];    char k;    int count=0;    puts("Enter file name:");    gets(name);    if((hi=fopen(name,"r"))==NULL)    {        puts("Open file error!");        exit(1);    }    strcpy(file,name);    strcat(file,".zp");    if((hl=fopen(file,"w"))==NULL)    {        puts("Open file error!");        exit(1);    }    while((k=getc(hi))!=EOF)    {        if(count++%3==0)            putc(k,hl);    }    if(fclose(hi)!=0 || fclose(hl)!=0)        puts("File close error!");    puts("Done!");    return 0;}
0 0
原创粉丝点击