C Primer Plus(第六版)13.11 编程练习 第5题

/* append.c -- appends files to a file */
#include
#include
#include
#define BUFSIZE 4096
#define SLEN 81

//13.11-5.exe abc.txt def.txt

void append(FILE *source, FILE *dest);
char * s_gets(char * st, int n);

int main (int argc, char *argv[] )
{
    FILE *fa, *fs;    // fa for append file, fs for source file
    int files = 0;  // number of files appended
    int ch;
    
    if (argc < 3)
        exit(EXIT_FAILURE);
    else
    {
        if ((fa = fopen(argv[1], "a+")) == NULL)
        {
            fprintf(stderr, "Can't open %s\n", argv[1]);
            exit(EXIT_FAILURE);
        }
        if (setvbuf(fa, NULL, _IOFBF, BUFSIZE) != 0)
        {
            fputs("Can't create output buffer\n", stderr);
            exit(EXIT_FAILURE);
        }

        if (strcmp(argv[2], argv[1]) == 0)
            fputs("Can't append file to itself\n",stderr);
        else if ((fs = fopen(argv[2], "r")) == NULL)
            fprintf(stderr, "Can't open %s\n", argv[2]);
        else
        {
            if (setvbuf(fs, NULL, _IOFBF, BUFSIZE) != 0)
            //要知道,在打开fs的时候,C标准库会为该文件流自动分配一个缓冲区,并采用默认的缓冲策略。如果我们不希望默认的策略,采用setvbuf去修改. 
                   fputs("Can't create input buffer\n",stderr);
            append(fs, fa);
            if (ferror(fs) != 0)
                fprintf(stderr,"Error in reading file %s.\n",
                    argv[2]);
            if (ferror(fa) != 0)
                fprintf(stderr,"Error in writing file %s.\n",
                    argv[1]);
            fclose(fs);
            files++;

            printf("Done appending. %d files appended.\n", files);
            rewind(fa);
            printf("%s contents:\n", argv[1]);
            while ((ch = getc(fa)) != EOF)
                putchar(ch);
            puts("\nDone displaying.");
            fclose(fa);
        }
    }
    return 0;
}

void append(FILE *source, FILE *dest)
{
    size_t bytes;
    static char temp[BUFSIZE]; // allocate once
    
    while ((bytes = fread(temp,sizeof(char),BUFSIZE,source)) > 0)
        fwrite(temp, sizeof (char), bytes, dest);
}


 

你可能感兴趣的:(C,Primer,Plus(第六版),c语言)