C primer plus 第13章编程练习

第一题:

#include<stdio.h>
#include<stdlib.h>

int main(void/*int argc, char *argv[]*/)
{
    int ch, argc;
    char argv[88];
    FILE *fp;
    unsigned long count = 0;

    printf("input argc and name:\n");
    scanf("%d %s", &argc, argv);
    printf("%d %s", argc, argv);
    if(argc != 2)
    {
        printf("usage: %s filename\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    if((fp = fopen(argv, "r")) == NULL)
    {
        printf("can't open %s\n", argv[1]);
        exit(EXIT_FAILURE);
    }
    while((ch = getc(fp)) != EOF)
    {
        putc(ch, stdout);
        count++;
    }
    fclose(fp);
    printf("file %s has %lu characters\n", argv, count);

    return 0;
}

第二题,第三题:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>

int main(int argc, char *argv[])
{
    int ch;
    FILE *fp, *out;
    char name[88];
    unsigned long count = 0;

    if(argc != 2)
    {
        printf("usage: %s filename\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    if((fp = fopen(argv[1], "r")) == NULL)
    {
        printf("can't open %s\n", argv[1]);
        exit(EXIT_FAILURE);
    }
    strncpy(name,argv[1],88);
    name[88] = '\0';
    strcat(name,".red");
    if((out = fopen(name,"w")) == NULL)
    {
        printf("can't creat output file.\n");
        exit(3);
    }
    while((ch = getc(fp)) != EOF)
    {
        putc(toupper(ch), out);
    }
    if(fclose(fp) != 0 || fclose(out) != 0)
        printf("file close error\n");

    return 0;
}

第四题:

#include<stdio.h>
#include<stdlib.h>

int main(int argc, char *argv[])
{
    int i;

    for(i = 1; i < argc; i++)
    {
        fprintf(stdout, "%s ", argv[i]);
    }
  
    return 0;
}

 第七题:

#include<stdio.h>
#include<stdlib.h>

void function_a(char **file_a, char **file_b);

int main(int argc, char *argv[])
{
    if(argc != 3)
    {
        printf("usage: %s filename filename\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    function_a(argv[1], argv[2]);

    return 0;
}

void function_a(char **file_a, char **file_b)
{
    int ch_a, ch_b;
    FILE *fp_a, *fp_b;
    fp_a = fopen(file_a, "r");
    fp_b = fopen(file_b, "r");


    if(fp_a == NULL || fp_b == NULL)
    {
        printf("can't open file\n");
        exit(EXIT_FAILURE);
    }

    while ((ch_a = getc(fp_a)) != EOF || (ch_b = getc(fp_b)) != EOF)
    {
        char arr1[256],arr2[256];//每次循环释放内存

        if(fgets(arr1, 256, fp_a))//fgets读取到第一个换行符结束
            fputs(arr1,stdout);
        if(fgets(arr2, 256, fp_b))
            fputs(arr2,stdout);
    }
    fclose(fp_a);
    fclose(fp_b);
}

猜你喜欢

转载自www.cnblogs.com/cokefentas/p/12356569.html