C primer plus第13章(文件输入/输出)习题

来源:互联网 发布:mobileselect.js 编辑:程序博客网 时间:2024/06/05 17:37

4

#include <stdio.h>#include <stdlib.h>/*#include <console.h>*/ /*mac下*/int main(int argc,char *argv[]){    FILE *fp;    double n;    double sum = 0.0;    int ct = 0;    //argc = ccommand(&argv); //对于mac    if(argc == 1)    {        fp = stdin;    }    else if(argc == 2)    {        if((fp = fopen(argv[1],"r")) == NULL)        {            fprintf(stderr,"Cant open %s\n",argv[1]);            exit(EXIT_FAILURE);        }    }    else    {        fprintf(stderr,"Usage:%s\n",argv[0]);        exit(EXIT_FAILURE);    }    while(fscanf(fp,"%lf",&n) == 1)    {        sum += n;        ++ct;    }    if(ct > 0)        printf("Average of %d values = %f\n",ct,sum/ct);    else        printf("No valid data1.\n");    return 0;}

5
#include <stdio.h>#include <stdlib.h>//定义缓冲区大小#define BUFF 256/*#include <console.h>*/ /*mac下*/int has_ch(char ch, const char * line);int main(int argc,char *argv[]){    FILE *fp;    //第一个参数的第一个字符    char ch = argv[1][0];    char line[BUFF];    int flag = 0;    //argc = ccommand(&argv); //对于mac    if(argc != 3)    {        fprintf(stderr,"Usage:%s\n",argv[0]);        exit(EXIT_FAILURE);    }    //打开文本流    if((fp = fopen(argv[2],"r")) == NULL)    {        fprintf(stderr,"Cant open %s\n",argv[2]);        exit(EXIT_FAILURE);    }    while(fgets(line,BUFF,fp) != NULL)    {        //如果行中有此字符则打印        if(has_ch(ch,line) == 1)            fputs(line,stdout);        flag = 1;    }    fclose(fp);    return 0;}//比对行中是否存在字符int has_ch(char ch, const char * line){    while(*line)    {        if(ch == *line++)        {            return 1;        }    }    return 0;}

编程题

1

#include <stdio.h>#include <stdlib.h>// c的exi() 原型int main(){    int ch;    FILE *fp;    long count = 0;    char arr[50];    char *p = arr;    puts("请输入文件名");    gets(p);    if((fp = fopen(p,"r")) == NULL)    {        printf("Can`t open %s\n",p);        exit(1);    }    while((ch = getc(fp)) != EOF)    {        putc(ch,stdout);//相当于putchar (ch)        count++;    }    fclose(fp);    printf("File %s has %ld characters\n",p,count);    return 0;}

2

#include <stdio.h>#include <stdlib.h>int main(int argc,char *argv[]){    int byte;    FILE *fp,*fp2;    if(argc != 3) {        fprintf(stderr,"argument not enough");        exit(EXIT_FAILURE);    }    if((fp = fopen(argv[1],"rb")) == NULL) {        fprintf(stderr,"%s can not open",argv[1]);        exit(EXIT_FAILURE);    }    if((fp2 = fopen(argv[2],"wb")) == NULL) {        fprintf(stderr,"%s can not open",argv[1]);        exit(EXIT_FAILURE);    }    while((byte = getc(fp)) != EOF) {        putc(byte,fp2);    }    fclose(fp);    fclose(fp2);    return 0;}

3

#include <stdio.h>#include <stdlib.h>#include <ctype.h>//复制文件,将文件源中字母转为大写后存入目标文件int main(){    char ch;    char f1[50];    char f2[50];    FILE *fp,*fp2;    printf("请输入源文件名:\n");    gets(f1);    if((fp = fopen(f1,"rb")) == NULL) {        fprintf(stderr,"%s can not open",f1);        exit(EXIT_FAILURE);    }    printf("请输入目标文件名:\n");    gets(f2);    if((fp2 = fopen(f2,"wb")) == NULL) {        fprintf(stderr,"%s can not open",f2);        exit(EXIT_FAILURE);    }    while((ch = getc(fp)) != EOF) {        ch = isupper(ch) ? ch : toupper(ch);        putc(ch,fp2);    }    fclose(fp);    fclose(fp2);    return 0;}

4

#include <stdio.h>#include <stdlib.h>//#include <console.h> //mac下需要//读取命令行文件名并打印内容int main(int argc,char *argv[]){    int i,j;    FILE *fp;    //下面两种定义方式都可以    //char ch;    int ch;    //argc = ccomand(&argv); //mac需要    if(argc == 1)    {        printf("没有相关文件");    }    for(i = 1; i<argc; i++)    {        if((fp = fopen(argv[i],"r")) == NULL)        {            printf("无法打开文件%s",argv[i]);            exit(EXIT_FAILURE);        }        while((ch = getc(fp)) != EOF)        {            putchar(ch);        }        if(fclose(fp) != 0)        {            printf("文件%s未正常关闭",argv[i]);        }    }    return 0;}

5

//原版(有问题)

#include <stdio.h>#include <stdlib.h>#include <string.h>#define BUFSIZE 1024#define SLEN 101void append(FILE *source,FILE *dest);//#include <console.h> //mac下需要//读取命令行文件名并打印内容int main(void){    FILE *fa,*fs;//fa指向追加的目的文件,fs指向源文件    int files = 0;//追加文件的个数    char file_app[SLEN];//被追加文件的名称    char file_src[SLEN];//源文件的名称    puts("Enter name of destination file:");    gets(file_app);    if((fa = fopen(file_app,"a")) == NULL)    {        fprintf(stderr,"Can`t open %s\n",file_app);        exit(2);    }    if(setvbuf(fa,NULL,_IOFBF,BUFSIZE) != 0)    {        fputs("Can`t create output buffer\n",stderr);        exit(3);    }    puts("Enter name of first source file(empty line to quit);");    while(gets(file_src) && file_src[0] != '\0')    {        if(strcmp(file_src,file_app) == 0)        {            fputs("Can`t append file to itself\n",stderr);        }        else if((fs = fopen(file_src,"r")) == NULL)        {            fprintf(stderr,"Can`t open %s\n",file_src);        }        else        {            if(setvbuf(fs,NULL,_IOFBF,BUFSIZE) != 0)            {                fputs("Can`t create input buffer\n",stderr);                continue;            }            append(fs,fa);            if(ferror(fs) != 0)            {                fprintf(stderr,"Error in reading file %s.\n",file_src);            }            if(ferror(fa) != 0)            {                fprintf(stderr,"Error in writing file %s.\n",file_app);            }            fclose(fs);            files++;            printf("File %d appended.\n",files);            puts("Next file(empty line to quit)");        }    }    printf("Done,%d files appended.\n",files);    fclose(fa);    return 0;}void append(FILE *source,FILE *dest){    //size_t代表无符号整型    size_t bytes;    static char temp[BUFSIZE];//分配一次    while((bytes = fread(temp,sizeof(char),BUFSIZE,source)) > 0)    {        fwrite(temp,sizeof(char),10,dest);    }}



6.

13.2原始

//将文件压缩为原来的三分之一#include <stdio.h>#include <stdlib.h>#include <string.h>//strcpy和strcat函数原型#define LEN 40//#include <console.h> //mac下需要//读取命令行文件名并打印内容int main(int argc,char *argv[]){    FILE *in,*out;//fa指向追加的目的文件,fs指向源文件    int ch;    char name[LEN];    int count = 0;    if(argc < 2)    {        fprintf(stderr,"Usage: %s filename\n",argv[0]);        exit(1);    }    if((in = fopen(argv[1],"r")) == NULL)    {        fprintf(stderr,"I couldn`t open the file\"%s\"",argv[1]);        exit(2);    }    strcpy(name,argv[1]);    strcat(name,"w");    if((out = fopen(name,"w")) == NULL)    {        fprintf(stderr,"Can`t create output file.\n");        exit(3);    }    while((ch = getc(in)) != EOF)    {        if(count++ %3 == 0)        {            putc(ch,out);        }    }    if(fclose(in) != 0 || fclose(out) != 0)    {        fprintf(stderr,"Error in closing files\n");    }    return 0;}


按题目修改

//将文件压缩为原来的三分之一#include <stdio.h>#include <stdlib.h>#include <string.h>//strcpy和strcat函数原型#define LEN 40//#include <console.h> //mac下需要//读取命令行文件名并打印内容int main(int argc,char *argv[]){    FILE *in,*out;//fa指向追加的目的文件,fs指向源文件    int ch;    char name[LEN];    int count = 0;    printf("请输入文件名");    gets(name);    if((in = fopen(name,"r")) == NULL)    {        fprintf(stderr,"I couldn`t open the file\"%s\"",name);        exit(2);    }    strcat(name,"w");    if((out = fopen(name,"w")) == NULL)    {        fprintf(stderr,"Can`t create output file.\n");        exit(3);    }    while((ch = getc(in)) != EOF)    {        if(count++ %3 == 0)        {            putc(ch,out);        }    }    if(fclose(in) != 0 || fclose(out) != 0)    {        fprintf(stderr,"Error in closing files\n");    }    return 0;}

7

//将文件压缩为原来的三分之一#include <stdio.h>#include <stdlib.h>#include <string.h>//strcpy和strcat函数原型#define LEN 40#define BUFSIZE 2048//#include <console.h> //mac下需要//读取命令行文件名并打印内容int main(int argc,char *argv[]){    FILE *fa,*fb;//fa指向追加的目的文件,fs指向源文件    char* f1,f2;    char name[LEN];    char temp[BUFSIZE];    int count = 0;    f1 = f2 = 1;    if(argc < 3)    {        fprintf(stderr,"Usage: %s filename\n",argv[0]);        exit(1);    }    if((fa = fopen(argv[1],"r")) == NULL)    {        fprintf(stderr,"I couldn`t open the file\"%s\"",argv[1]);        exit(2);    }    if((fb = fopen(argv[2],"r")) == NULL)    {        fprintf(stderr,"I couldn`t open the file\"%s\"",argv[2]);        exit(2);    }    if(setvbuf(fa,NULL,_IOFBF,BUFSIZE)!=0 || setvbuf(fb,NULL,_IOFBF,BUFSIZE)!=0)    {        fprintf("Can`t create output buffer\n",stderr);        exit(3);    }    while(f1!=NULL || f2 !=NULL)    {        if(f1 != NULL)        {            f1 = fgets(temp,BUFSIZE,fa);            if(temp[strlen(temp)-1] == '\n')            {                temp[strlen(temp)-1] = 0;            }            printf("%s ",temp);        }        if(f2 != NULL)        {            f2 = fgets(temp,BUFSIZE,fb);            if(temp[strlen(temp)-1] == '\n')            {                temp[strlen(temp)-1] = 0;            }            printf("%s ",temp);        }        putchar('\n');    }    if(fclose(fa) != 0 || fclose(fb) != 0)    {        fprintf(stderr,"Error in closing files\n");    }    return 0;}

8

#include <stdio.h>#include <stdlib.h>#include <string.h>#define SLEN 101void check(size_t t,char *f);//#include <console.h> //mac下需要int main(int argc,char *argv[]){    int i;    size_t t;    char f[SLEN];    if(argc < 2)    {        fprintf(stderr,"缺少参数!");        exit(EXIT_FAILURE);    }    t = argv[1][0];    if(argc == 2)    {        printf("请输入文件名:");        while(fgets(f,SLEN,stdin) != NULL)        {            //去掉换行符            f[strlen(f)-1] = 0;            check(t,f);            printf("请输入文件名:");        }    }    else    {        for(i = 2; i<argc; i++)        {            check(t,argv[i]);        }    }    return 0;}void check(size_t t,char *f){    FILE *fi;    if((fi = fopen(f,"r")) == NULL)    {        printf("文件%s打开错误",f);    }    size_t bytes,count;    count = 0;    while((bytes = getc(fi)) != EOF)    {        if(bytes == t)        {            count++;        }    }    fclose(fi);    printf("文件%s共包含%d个%c字符。\n",f,count,t);}

9

13.3原型

#include <stdio.h>#include <stdlib.h>#define MAX 40//#include <console.h> //mac下需要int main(void){    FILE *fp;    size_t bytes;    int no;    char words[MAX];    if((fp = fopen("d:/words.txt","a+")) == NULL)    {        fprintf(stdout,"Can`t open \"words\" file.\n");        exit(1);    }    puts("Enter words to add to the file;press the Enter");    puts("key at the beginning of a line to terminate");    while(gets(words) != NULL && words[0] != '\0')    {        fprintf(fp,"%s",words);    }    puts("File contents:");    rewind(fp);//回到文件的开始处    while(fscanf(fp,"%s",words) == 1)    {        puts(words);    }    if(fclose(fp) != 0)    {        fprintf(stderr,"Error closing file\n");    }    return 0;}


修改后,数字编号

#include <stdio.h>#include <stdlib.h>#define MAX 256//#include <console.h> //mac下需要int main(void){    FILE *fp;    size_t bytes;    int no = 0;    char words[MAX];    if((fp = fopen("d:/words.txt","a+")) == NULL)    {        fprintf(stdout,"Can`t open \"words\" file.\n");        exit(1);    }    puts("Enter words to add to the file;press the Enter");    puts("key at the beginning of a line to terminate");    while((bytes = fgetc(fp)) != EOF)    {        if(bytes == ':')        {            no++;        }    }    rewind(fp);    while(gets(words) != NULL && words[0] != '\0')    {        fprintf(fp,"%d:%s",++no,words);    }    puts("File contents:");    rewind(fp);//回到文件的开始处    while(fscanf(fp,"%s",words) == 1)    {        puts(words);    }    if(fclose(fp) != 0)    {        fprintf(stderr,"Error closing file\n");    }    return 0;}

10

//将文件压缩为原来的三分之一#include <stdio.h>#include <stdlib.h>#define LEN 40//#include <console.h> //mac下需要//读取命令行文件名并打印内容int main(int argc,char *argv[]){    char fileName[LEN];    FILE *fb;    int pos;    size_t bytes;    printf("请输入文件名:");    gets(fileName);    if((fb = fopen(fileName,"r")) == NULL)    {        fprintf(stderr,"文件%s不能打开",fileName);        exit(EXIT_FAILURE);    }    printf("请输入开始读取的位置:");    while(scanf("%d",&pos) == 1)    {        fseek(fb,pos,SEEK_SET);        while((bytes = getc(fb))!=EOF)        {            putchar(bytes);        }        printf("\n请输入开始读取的位置:");    }    return 0;}

11

#include <stdio.h>#include <stdlib.h>#include <string.h>#define LINE 256//#include <console.h> //mac下需要int main(int argc,char*argv[]){    FILE *fp;    char line[LINE];    if(argc != 3)    {        fprintf(stderr,"参数错误!");        exit(EXIT_FAILURE);    }    if((fp = fopen(argv[2],"r"))== NULL)    {        fprintf(stderr,"不能打开文件%s",argv[2]);    }    while(fgets(line,LINE,fp) != NULL)    {        if(strstr(line,argv[1]) != NULL)        {            fputs(line,stdout);        }    }    return 0;}

12

#include <stdio.h>#include <stdlib.h>#define ROWS 20#define COLS 30#define LEVELS 10const char trans[LEVELS +1] = " .':~*=&%@";void MakePic(int data[][COLS],char pic[][COLS],int rows);void init(char arr[][COLS],char ch);//#include <console.h> //macÏÂÐèÒªint main(void){    int row,col;    int picIn[ROWS][COLS];    char picOut[ROWS][COLS];    char fileName[40];    FILE * infile;    //初始化输出数组(用不用一样)    init(picOut,'S');    printf("Enter name of file;");    scanf("%s",fileName);    if((infile = fopen(fileName,"r")) == NULL)    {        fprintf(stderr,"Could not oopen data file.\n");        exit(EXIT_FAILURE);    }    //将文本中的数字读入数组    for(row = 0; row <ROWS; row++)    {        for(col = 0; col <COLS; col++)        {            //从一个流中执行格式化输入,fscanf遇到空格和换行时结束,注意空格时也结束。            fscanf(infile,"%d",&picIn[row][col]);        }    }    if(ferror(infile))    {        fprintf(stderr,"Error getting data from file.\n");        exit(EXIT_FAILURE);    }    //将数字转换成符号    MakePic(picIn,picOut,ROWS);    //输出    for(row = 0; row < ROWS; row++)    {        for(col = 0; col <COLS; col++)        {            putchar(picOut[row][col]);        }        putchar('\n');    }    return 0;}void init(char arr[][COLS],char ch){    int r,c;    for(r = 0; r< ROWS; r++)    {        for(c=0; c<COLS; c++)        {            arr[r][c] = ch;        }    }}//将data数组的值转换成trans中的符号后录入picvoid MakePic(int data[][COLS],char pic[][COLS],int rows){    int row,col;    for(row = 0; row <rows; row++)    {        for(col = 0; col <COLS; col++)        {            pic[row][col] = trans[data[row][col]];        }    }}
文件

0 0 9 0 0 0 0 0 0 0 0 5 6 7 8 9 0 1 2 3 4 5 6 7 2 3 4 5 6 1
0 0 9 0 0 0 0 0 0 0 0 5 6 7 8 9 0 1 2 3 4 5 6 7 2 3 4 5 6 1
0 0 9 0 0 0 0 0 0 0 0 5 6 7 8 9 0 1 2 3 4 5 6 7 2 3 4 5 6 1
0 0 9 0 0 0 0 0 0 0 0 5 6 7 8 9 0 1 2 3 4 5 6 7 2 3 4 5 6 1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&%@";void MakePic(int data[][COLS],char pic[][COLS],int rows);void init(char arr[][COLS],char ch);int check (int a,int b,FILE *infile,int *sum, int *no);//#include <console.h> //macÏÂÐèÒªint main(void){    int row,col;    int picIn[ROWS][COLS];    char picOut[ROWS][COLS];    char fileName[40];    FILE * infile;    //初始化输出数组(用不用一样)    init(picOut,'S');    printf("Enter name of file:");    scanf("%s",fileName);    if((infile = fopen(fileName,"r")) == NULL)    {        fprintf(stderr,"Could not oopen data file.\n");        exit(EXIT_FAILURE);    }    int no = 0;    int sum = 0;    //将文本中的数字读入数组    for(row = 0; row <ROWS; row++)    {        for(col = 0; col <COLS; col++)        {            //从一个流中执行格式化输入,fscanf遇到空格和换行时结束,注意空格时也结束。            fscanf(infile,"%d",&picIn[row][col]);        }    }    if(ferror(infile))    {        fprintf(stderr,"Error getting data from file.\n");        exit(EXIT_FAILURE);    }    //消除峰值    for(row = 0; row <ROWS; row++)    {        for(col = 0; col <COLS; col++)        {            if((row != 0 && check (picIn[row][col],picIn[row-1][col],infile,&sum,&no) == 0)                    ||(row != 19&& check (picIn[row][col],picIn[row+1][col],infile,&sum,&no) == 0)                    ||(col != 0&& check (picIn[row][col],picIn[row][col-1],infile,&sum,&no) == 0)                    ||(col != 29&& check (picIn[row][col],picIn[row][col+1],infile,&sum,&no) == 0) )            {                continue;            }            picIn[row][col] =  sum/no;        }    }    /*    for(row = 0; row <ROWS; row++)    {        for(col = 0; col <COLS; col++)        {            printf("%d",picIn[row][col]);        }        putchar('\n');    }    return 0;    */    //将数字转换成符号    MakePic(picIn,picOut,ROWS);    //输出    for(row = 0; row < ROWS; row++)    {        for(col = 0; col <COLS; col++)        {            putchar(picOut[row][col]);        }        putchar('\n');    }    return 0;}void init(char arr[][COLS],char ch){    int r,c;    for(r = 0; r< ROWS; r++)    {        for(c=0; c<COLS; c++)        {            arr[r][c] = ch;        }    }}//将data数组的值转换成trans中的符号后录入picvoid MakePic(int data[][COLS],char pic[][COLS],int rows){    int row,col;    for(row = 0; row <rows; row++)    {        for(col = 0; col <COLS; col++)        {            pic[row][col] = trans[data[row][col]];        }    }}//检验是否尖峰脉冲int check (int a,int b,FILE *infile,int *sum, int *no){    if(a == b)    {        return 0;    }    (*sum) += b;    (*no)++;    return 1;}


原创粉丝点击