Làm thế nào để vừa đọc từ file này và in ra file khác/màn hình?

Em muốn hỏi hàm này khi đọc từ 1 tập tin khác chỉ xuất dc 1 cái ví dụ như xuất ra file khác hay xuất ra màn hình Vậy thì làm sao xuất ra đồng thời cả 2 ạ .

#include<stdio.h>
#include<stdlib.h>
void transFile(FILE* infile, FILE* outfile)
{
	int ch;
	while (1)
	{
		ch = fgetc(infile);
		if (!feof(infile))
			fputc(ch, outfile);
		else
			break;
	}
}
int main()
{
	FILE* fpIn;
	char* fname = "Data.txt";
	fpIn = fopen(fname, "r");
	
	if (fpIn == NULL)
	{
		printf("File %s not found!\n", fname);
		return 0;
	}
	
	transFile(fpIn, stdout);

	FILE* fpOut;
	char* fname2 = "Output.txt";
	fpOut = fopen(fname2, "w");
	if (fpIn == NULL)
	{
		printf("File %s not found!\n", fname);
		fclose(fpIn);
		return 0;
	}
	transFile(fpIn, fpOut);

	fclose(fpOut);
	fclose(stdout);

	fclose(fpIn);
	
	system("pause");
	return 0;
}

Dùng fprintf để in ra file và printf để in ra màn hình.

ý em nói là dùng hàm á

Mình vẫn chưa hiểu bạn định hỏi gì.

khi em muốn xuất ra màn hình thì goi laị hàm transFile(fpIn,stdout) còn xuất ra fle khác thì transFile(fpIn,fileout) . Cái hàm đó chỉ xuất ra 1 lần rồi xóa trong bộ nhớ đệm nên khi em viết transFile(fpIn,stdout); transFile(fpIn,fileout) ; thì chỉ xuất ra màn hình nên em muốn cho ra cả 2 thì phải làm sao

Bạn chuyển đổi transFile để gộp thành vừa in ra file, vừa in ra stdout luôn:

void transFile(FILE* infile, FILE* outfile)
{
	int ch;
	while (1)
	{
		ch = fgetc(infile);
		if (!feof(infile)) {
			fputc(ch, outfile);
			// in ra màn hình luôn
		} else
			break;
	}
}

vậy là thêm 1 lệnh fputc(ch,outfile1) nữa phải ko ad ?

void transFile(FILE* infile, FILE* outfile,FILE* outfile1)
{
	char ch;
	while (1)
	{
		ch = fgetc(infile);
		if (feof(infile))
			break;
		else
		{
			
			int pos = ftell(infile);
			fputc(ch, outfile);
			fseek(infile, pos - 1, 0);
			ch = fgetc(infile);
			fputc(ch, outfile1);
		}

	}
}

Thêm tham số outfile1 làm gì nữa cho mệt, cứ in thẳng ra stdout ấy.

Ở đây chỉ có 1 ad, và người đó không phải mình.

1 Like
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?