首页 > 代码库 > C C++基本输入输出

C C++基本输入输出

//#include<stdio.h>
#include<fstream>
#include<iostream>
//http://www.cnblogs.com/Yogurshine/p/3677201.html
using namespace std;
#define ERROR 1
#define OK    0

int WriteFileWithCStyle()
{
	float f[6]={3.2f,-4.34f,25.04f,0.1f,50.56f,80.5f};
	FILE *fp;
	fp=fopen("1.txt","w");
	if(NULL==fp)
	{
		return ERROR;
	}
	//fwrite(f,sizeof(float),sizeof(f)/sizeof(float),fp);//二进制
	for(int i=0;i<6;i++)
	{
		fprintf(fp,"%f ",f[i]);//ASIC
	}
	
	fclose(fp);
	return OK;
}
int ReadFileWithCStyle()
{
	float f[6]={0.0};
	FILE *fp;
	fp=fopen("1.txt","r");
	if(NULL == fp)
	{
		return ERROR;
	}
	/*fread(f,sizeof(float),6,fp);//二进制

	fclose(fp);
	for(int i=0;i<6;i++)
	{
		printf("f[%d] value[%2f]\r\n",i,f[i]);
	}*/
	for(int i=0;i<6;i++)
	{
		fscanf(fp, "%f", &f[i]); 
		printf("f[%d] value[%2f]\r\n",i,f[i]);
	}
	 

	return OK;
	
}

int WriteFileWithCPPStyle()
{
	fstream file1;
	file1.open("2.txt");
	if(!file1)
	{
		cout<<"oepn error"<<endl;
	}
	char a[10];
	char b[10];
	//写入文件
	for(int i=0;i<10;i++)
	{
		cin>>a[i];
		file1<<a[i]<<" ";
	}
	file1.close();
	fstream file2;
	file2.open("2.txt");
	if(!file2)
	{
		cout<<"oepn error"<<endl;
	}
	//从文件中读取
	for(int i=0;i<10;i++)
	{
		file2>>b[i];
		cout<<b[i]<<" ";
	}

	file2.close();





	return OK;
}
int main()
{
	WriteFileWithCStyle();
	ReadFileWithCStyle();
	WriteFileWithCPPStyle();

	return OK;
}

 

C C++基本输入输出