0
假設我有一個將結果打印到文件的程序。但是我想要將相同的結果打印到另一個文件和命令行中。我試圖創建另一個文件,但我不斷收到錯誤:當對該文件進行錯誤檢查時,「下標值既不是數組也不是指針」。我會如何去做這件事?這是我的節目裏,結果被打印到一個文件:如何輸出到C中的兩個單獨的文件和命令行?
#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()'? – exebook
要寫入另一個文件,您只需聲明一個文件描述符並再次調用'fopen()'。那有什麼問題呢? – exebook
printf只打印到控制檯而不是文件? – user2264035