将文件列表合并到另一个文件中

时间:2016-06-24 21:31:06

标签: c fopen fclose fgetc

我试图创建一个程序来获取一系列文件并将它们复制到另一个文件中。

例如

  

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

必须使用arch1.txt arch2.txt,archN.txt的内容创建arch3.txt。

这是我的代码:

#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;
}

我的产品:

  

无法打开文件:./ foobar

3 个答案:

答案 0 :(得分:1)

那是因为您在fopen()中使用* argv作为fi​​lename参数。它应该是argv [argc - 1]。

答案 1 :(得分:1)

*argv不是第一个参数,而是可执行文件的路径。

在直接使用之前增加argv一次:

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

或者更好地使用数组索引并从argv[1]开始。

答案 2 :(得分:0)

我修好了。它不漂亮,但它现在有效。

#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;
}