0

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

Telefang
  • 133
  • 1
  • 15

3 Answers3

1

That's because you're using *argv for the filename parameter in fopen(). It should be argv[argc - 1].

Jay Cohen
  • 11
  • 2
  • The code iterates forward, so you'd want to start at -`argv[1]`, or given the iteration method just place `argv++` before the call to `fopen()` – Clifford Jun 24 '16 at 21:44
1

*argv is not the first argument, but rather the path of the executable.

Increment argv once before using it directly:

    argv++ ;
    if ((fp2 = fopen(argv[argc-1], "w")) == NULL) {

or perhaps better use array indexing and start from argv[1].

Clifford
  • 88,407
  • 13
  • 85
  • 165
0

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;
}
Telefang
  • 133
  • 1
  • 15