c - 如何在 C 中输出到两个单独的文件和命令行?

标签 c file-io command-line output printf

假设我有一个将结果打印到文件的程序。但我希望将相同的结果打印到另一个文件和命令行中。我尝试创建另一个文件,但在对该文件进行错误检查时不断收到错误:“下标值既不是数组也不是指针”。我该怎么做呢?这是我的程序,其中结果被打印到一个文件中:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
    int offset;
    int ch1, ch2;
    FILE *fh1, *fh2, *diffone=stdout;


    if( argc<3 ) {
        printf("need two file names\n"); return(1);
    }
    if(!(fh1 = fopen(argv[1], "r"))) {
        printf("cannot open %s\n",argv[1]); return(2);
    }
    if(!(fh2 = fopen(argv[2], "r"))) {
        printf("cannot open %s\n",argv[2]); return(3);
    }
    if(argc>3) {
        if(!(diffone = fopen(argv[3], "w+"))) {
            printf("cannot open %s\n",argv[3]); return(4);
        }
    }

    while((!feof(fh1)) && (!feof(fh2)))
    {
        ch1=ch2='-';
        if(!feof(fh1)) ch1 = getc(fh1);
        if(!feof(fh2)) ch2 = getc(fh2);
        if(ch1 != ch2)
            fprintf(diffone,"%c", ch1);//How do I print this to another file and the command line as well?
      }


    return 0;
}

最佳答案

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
     int offset;
     int ch1, ch2;
     FILE *fh1, *fh2, *diffone=stdout, *file2=0;


     if( argc<3 ) {
          printf("need two file names\n"); return(1);
     }
     if(!(fh1 = fopen(argv[1], "r"))) {
          printf("cannot open %s\n",argv[1]); return(2);
     }
     if(!(fh2 = fopen(argv[2], "r"))) {
          printf("cannot open %s\n",argv[2]); return(3);
     }
     if(argc>3) {
          if(!(diffone = fopen(argv[3], "w+"))) {
                printf("cannot open %s\n",argv[3]); return(4);
          }
     }
     if(argc>4) {
          if(!(file2 = fopen(argv[4], "w+"))) {
                printf("cannot open %s\n",argv[4]); return(4);
          }
     }

     while((!feof(fh1)) && (!feof(fh2)))
     {
          ch1=ch2='-';
          if(!feof(fh1)) ch1 = getc(fh1);
          if(!feof(fh2)) ch2 = getc(fh2);
          if(ch1 != ch2) {
                fprintf(diffone,"%c", ch1);//print to a console or file depending on the value of diffone
                if (file2) fprintf(file2,"%c", ch1);
          }
        }


     return 0;
}

关于c - 如何在 C 中输出到两个单独的文件和命令行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19697603/

相关文章:

c++ - 来自终端的base64编码字符串?

java - 将命令行中的文本获取到 Java 中

python - 如何在脚本仍在运行时使 shell 输出重定向 (>) 写入?

c - 链表仍然相关吗?

c - 为什么我的系统中有这么多版本的头文件?

c - 是否有必要将 0 传递给数组

c++ - 写入多个文件的 fclose、fopen 和 fwrite 问题

java - 快速写入文件 - 有时文件为空

c - union 无法解码字节数组

c - C 中的指针、文件和内存管理