1. 程式人生 > >c語言從一個檔案讀取文字到另一個檔案中

c語言從一個檔案讀取文字到另一個檔案中

#include "stdio.h"
#include "string.h"
int main()
{
	FILE *fileR, *fileW;
	char buf[1000];
	if((fileR = fopen("test.txt","r")) == NULL)
		printf("open error!\n");

	if((fileW = fopen("result.txt","w")) == NULL)
		printf("wirte opened error!\n");
	int i=0,size=0;
	char ch=fgetc(fileR);
	while(ch != EOF)
	{
		buf[i++]=ch;
		fwrite(&ch, 1, 1, fileW);
		ch=fgetc(fileR);
		size++;
	}

	//用下面方法寫出來的最後有點小bug
/*	while(!feof(fileR))
	{
		fread(&buf[i], 1, 1, fileR);
		fwrite(&buf[i], 1, 1, fileW);
		i++;
		size++;
	}*/

	for(i = 0; i < size; i++)
	   printf("%c", buf[i]);
	fclose(fileR);
	fclose(fileW);

	return 0;
}