[C/C++] C/C++語言文件讀寫函數

學習自“知道螞蟻” 點擊打開鏈接

#include <stdlib.h>
#include <stdio.h>

using namespace std;

int main()
{
	FILE *fpSrc, *fpDes;
	fpSrc = fopen("execute.stdin", "r");   // 打開[沒有則創建]文件讀取數據
	fpDes = fopen("destfile.stdin", "w");  // 打開文件寫入數據
	if (fpSrc == NULL || fpDes == NULL)
	{
		printf("文件打開錯誤!");
		exit(-1); // 非正常退出
	}
	
	char cVal;
	while ((cVal = fgetc(fpSrc)) != EOF)  // 判斷是否讀完文件
	{
		fputc(cVal, fpDes);				  // 將源文件中內容複製大目標文件
	}



	fclose(fpSrc);
	fclose(fpDes); // fcloseall(); 關閉多個文件

	system("pause");
	return 0;
}

/*
C++

代碼如下:
*/
#include <iostream>
#include <fstream>


using namespace std;


int main()
{
	ifstream ifs("execute.stdin");
	ofstream ofs("destfile.stdin");
	int iVal;
	while ( ifs >> iVal )  // 判斷是否讀完文件
	{
		ofs << iVal;				  // 將源文件中內容複製大目標文件
	}


	ifs.close();
	ofs.close();


	system("pause");
	return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章