18.C++的IO流

standard_in and standard_out

- standard_in (key_board) - standard_out (screen)


C和C++输入输出的比较


#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<fstream>
using namespace std;

void TestCWrite(int ar[], int n)
{
	FILE *fp = fopen("Test1.txt", "w");
	if(fp == NULL)
	{
		return;
	}

	for(int i=0; i<n; ++i)
	{
		fprintf(fp, "%d ", ar[i]);  //格式化输出
	}

	fclose(fp);
}

void TestCRead(int ar[], int n)
{
	FILE *fp = fopen("Test1.txt", "r");
	if(fp == NULL)
		return;

	for(int i=0; i<n; ++i)
	{
		(void)fscanf(fp, "%d", &ar[i]);  //格式化输入
	}

	fclose(fp);
}

void TestCppWrite(int ar[], int n)
{
	//ofstream ofile;  //1
	//ofile.open("Test2.txt", ios::out);  //2

	ofstream ofile("Test3.txt", ios::out);  //1+2

	if(!ofile)
	{
		cout<<"Open File Error."<<endl;
		return;
	}

	for(int i=0; i<n; ++i)
	{
		ofile<<ar[i]<<" ";  //3
	}

	ofile.close();     //4
}

void TestCppRead(int ar[], int n)
{
	ifstream ifile;
	ifile.open("Test2.txt", ios::in);
	if(!ifile)
		return;

	for(int i=0; i<n; ++i)
	{
		ifile>>ar[i];
	}

	ifile.close();
}

//
//二进制文件
void TestCBinWrite(int ar[], int n)
{
	FILE *fp = fopen("Test3.txt", "wb");
	if(fp == NULL)
	{
		return;
	}
	fwrite(ar, sizeof(int), n, fp); //C
	fclose(fp);
}

void TestCBinRead(int ar[], int n)
{
	FILE *fp = fopen("Test3.txt", "rb");
	if(fp == NULL)
		return;

	fread(ar, sizeof(int), n, fp);

	fclose(fp);
}

void TestCppBinWrite(int ar[], int n)
{
	//ofstream ofile;  //1
	//ofile.open("Test2.txt", ios::out);  //2

	ofstream ofile("Test4.txt", ios::out|ios::binary);

	if(!ofile)
	{
		cout<<"Open File Error."<<endl;
		return;
	}

	ofile.write((const char*)ar, sizeof(int) * n);

	ofile.close();     //4
}

void TestCppBinRead(int ar[], int n)
{
	ifstream ifile;
	ifile.open("Test4.txt", ios::in|ios::binary);
	if(!ifile)
		return;

	ifile.read((char*)ar, sizeof(int) * n);

	ifile.close();
}

void main()
{
	int ar[] = {12,23,34,45,56,67,78,89,90,100};
	int n = sizeof(ar) / sizeof(int);
	//TestCWrite(ar, n);
	//TestCppWrite(ar, n);

	int br[10];
	int cr[10];
	//TestCRead(br, 10);
	//TestCppRead(cr, 10);

	//TestCBinWrite(ar, n);
	//TestCppBinWrite(ar, n);

	TestCBinRead(br, 10);
	TestCppBinRead(cr, 10);

}


随机读写fseek

void main()
{
	FILE *fp = fopen("Test1.txt","r");
	int pos = 1;
	int value;
	while(1)
	{
		cout<<"input pos:>";
		cin>>pos;

		fseek(fp, pos*3, SEEK_SET);
		(void)fscanf(fp, "%d", &value);
		printf("value = %d\n", value);

	}
	fclose(fp);
}

setwidth
uperr

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值