gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:45:14 25 4
gpt4 key购买 nike

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

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com