-6

我正在尝试在第二个文件(b.txt)的末尾添加第一个文件(a.txt)的内容......但我不知道该怎么做。我有以下代码。

        int i = 0;
        char delims[] = " \n";
        char *result = NULL;
        char * results[10];
        result = strtok( cmdStr, delims );
        while( result != NULL ) {
            results[i] = result;
            i++;
            result = strtok(NULL, " \n");
        }

        // results[1] shows a.txt
        // results[2] shows b.txt

        FILE *fp;
        char ch;

        if((fp = fopen(results[1],"r")) == NULL) {
            printf("Cannot open file.\n");
        } else {
            ...
            // add the content of results[1] in the end of results[2]
            ...
        }
        fclose(fp);

Results[1] 是文件 a.txt 的名称。Results[2] 是文件 b.txt 的名称。

谢谢。

4

1 回答 1

0

results[2]以追加模式打开:

FILE *fp2;

fp2 = fopen(results[2], "a");  // a is for append

然后你可以遍历第一个文件并转储到第二个文件..类似于:

char line[100] = {0};
while (fgets(line,sizeof(line),fp) != NULL)
  fputs(line, fp2);

编辑:这是一个完整的编译程序,它获取“test.txt”的内容并将其附加到“test2.txt”:

int main(int argc, char** argv) {
    FILE *fp;
    FILE *fp2;
    char line[100] = {0};
    char * results[2] = {"test.txt", "test2.txt"};
    fp = fopen(results[0], "r");
    fp2 = fopen(results[1], "a");  // a is for append

    while (fgets(line,sizeof(line),fp) != NULL)
       fputs(line, fp2);
    fclose(fp);
    fclose(fp2);
    return 0;
}
于 2012-12-13T19:33:24.977 回答