Search code examples
cfopenfclosefgetc

Merging a list of files into another


I'm trying to make a program that takes a series of files and copies them into another one.

for example

./foobar arch1.txt arch2.txt arch3.txt

must create arch3.txt with the contents of arch1.txt arch2.txt, archN.txt.

This is my code:

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


void usage (char *argv[], int code)
{
    printf("usage: %s [<file> <out_file>] \n", argv[0]);
    exit(code);
}

void copyFile (FILE *ifp, FILE *ofp)
{
    int c;

    while ((c = fgetc(ifp)) != EOF) 
        fputc(c, ofp);
}

int main(int argc, char *argv[])
{
    system ("clear");

    FILE *fp, *fp2;

    if (argc < 3)
        usage(argv, EXIT_FAILURE);
    else
        if ((fp2 = fopen(argv[argc-1], "w")) == NULL) {
                    printf("Can't open file to write: %s\n", *argv);
                    exit(EXIT_FAILURE);
            }
        while(--argc > 0)
            printf("%d",argc);
            if ((fp = fopen(*++argv, "r")) == NULL) {
                printf("Can't open file: %s\n", *argv);
                exit(EXIT_FAILURE);
            }
            else {
                copyFile(fp, fp2);
                fclose(fp);
                fclose(fp2);    
            }
        return 0;
}

My ouput:

Can't open file to write: ./foobar


Solution

  • I fixed it. It's not pretty but it works now.

    #include <stdio.h>
    #include <stdlib.h>
    
    void usage (char *argv[], int code)
    {
        printf("usage: %s [<file> <out_file>] \n", argv[0]);
        exit(code);
    }
    
    void copyFile (FILE *ifp, FILE *ofp)
    {
        int c;
    
        while ((c = fgetc(ifp)) != EOF) 
            fputc(c, ofp);
    }
    
    int main(int argc, char *argv[])
    {
        FILE *f_read, *f_write;
    
        int i;
    
        if (argc < 3) 
            usage(argv, EXIT_FAILURE);
    
        if ((f_write = fopen(argv[argc-1], "w")) == NULL) {
            printf("Can't write in: %s\n", argv[argc-1]);
            exit(EXIT_FAILURE);
        }
    
        for (i = 1; i < argc-1; ++i)
        {
            if ((f_read = fopen(argv[i], "r")) == NULL) {
                    printf("Can't open file: %s\n", argv[i]);
                    exit(EXIT_FAILURE);
                }
                else
                    copyFile(f_read, f_write);
        }
        fclose(f_read);
        fclose(f_write);
        return 0;
    }