【问题标题】:How to output to two separate files and command line in C?如何在C中输出到两个单独的文件和命令行?
【发布时间】:2013-10-31 02:45:42
【问题描述】:

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

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

【问题讨论】:

  • 它对我有用。如果你想输出到控制台,为什么不直接使用printf 而不是fprintf()
  • 要写入另一个文件,您只需声明一个文件描述符并再调用一次fopen()。那有什么问题呢?
  • printf 是否只打印到控制台而不打印到文件?

标签: c file-io command-line output printf


【解决方案1】:
#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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多