C++ file操作



#include <fstream>
#include <stdio.h>
#include <iostream>
#include <string>// not <string.h>
#include <stdlib.h>
using namespace std;

#define MAX_LINE_LEN 100

typedef struct people
{
	int sno;
	char name[20];
}stu;

struct student
{
   string name;
   int num;
   int age;
   char sex;
};
//不同类型文件读写  不同读写方式
//追加写数据
//如何格式化或者分隔字符串方式从文件中读取数据  
//二进制文件读写
/*
  类          参数的默认方式 
ofstream ios::out | ios::trunc // ios::trunc 如果文件已存在则先删除该文件 
ifstream ios::in 
fstream ios::in | ios::out 
*/

void readbyline()//使用getline(fstream &fs,string & str)方法,读取文件到str
{
	char buffer[MAX_LINE_LEN];
	ifstream in("male.txt");
	if(!in.is_open())
	{
		cout<<"open file failed!\n"<<endl;
		exit(1);
	}
	while(!in.eof())
	{
		in.getline(buffer,MAX_LINE_LEN);//.....
		cout<<buffer<<endl;
	}
	in.close();
}


void writefilebystream()//使用插入器(<<) *写*文件
{
	char * name = "d";
	int position;

	//ofstream logfile("log.txt");
	ofstream logfile; 
	logfile.open("log.txt");//默认值为 ios::out | ios::trunc 文件已存在则先删除该文件
	logfile<<name;  //
	position=logfile.tellp();//pro1:获取当前文件写指针的位置  写文件的时候 指针前移,再写?
	cout<<"write pointer:"<<position<<endl;
	logfile.seekp(position,ios::beg);//设置文件写指针位置  **紧跟刚才的位置写文件**

	position=logfile.tellp();//获取当前文件写指针的位置
	cout<<"after seekp,write pointer:"<<position<<endl;

	logfile<<"good";
	logfile.close();
}

void readfilebystream()//使用析取器(>>)读文件
{
	ifstream readfile("log.txt");
	int position;
	if(!readfile.is_open())
	{
		cout<<"open file failed!\n"<<endl;
		exit(1);
	}

	string name;

	readfile>>name;
	position=readfile.tellg();//获取当前文件读指针的位置
	cout<<"name="<<name<<endl;
	cout<<"read pointer:"<<position<<endl;

	readfile.close();
}

void readbychar()//file2.get(x);表示从文件中读取一个字符,并把读取的字符保存在x中
{
	ifstream readfile("log.txt");
	char ch = NULL;
	while(readfile.get(ch))//
	{
		cout<<"char is :"<<ch<<endl;//
	}
	readfile.close();
}

void writebychar()//file1.put('c');就是向流写一个字符'c'。 
{
	ofstream out;
	string name;
	int i;
	out.open("log.txt",ios::out|ios::app);//pro3:   (ios::out|ios::app)或(ios:app) |不是||
	if(!out.is_open())
	{
		cout<<"open file failed!\n"<<endl;
		exit(1);
	}
	while(getline(cin,name)&&name.size()>0)
	{
		out<<name<<endl;//write file
	}
	
	for(i=0;i<5;i++)
		out.put(i+'0');//write file
	out.close();
}


//二进制文件
void writebinary()
{
	ofstream binout("a.dat",ios::binary|ios::out);
	int num=20;
	string str("hello world");
	stu sup_stu={1,"shentan"};
	//write(const unsigned char *buf,int num);
	//注意类型转换
	binout.write((char *)&num,sizeof(num));
	binout.write((char *)&str,sizeof(str));//写string型数据  不要用str.size()
	binout.write((char *)&sup_stu,sizeof(sup_stu));
	binout.close();
}

void readbinary()
{
	ifstream bin("a.dat",ios::binary|ios::in);
	int num;
	string str;
	stu sup_stu;
	//read(unsigned char *buf,int num);
	bin.read((char *)&num,sizeof(num));
	bin.read((char *)&str,sizeof(str));//读string型  
	bin.read((char *)&sup_stu,sizeof(sup_stu));
	cout<<num<<endl;
	cout<<str<<endl;
	cout<<sup_stu.sno<<" "<<sup_stu.name<<endl;
	bin.close();
}

void writestu()
{
	student stud[3]={"Li",1001,18,'f',"Fun",1002,19,'m',"Wang",1004,17,'f'};
	ofstream outfile("stud.dat",ios::binary);
	if(!outfile)
	{
		cerr<<"open error!"<<endl;
		exit(1);
   }
	for(int i=0;i<3;i++)
		outfile.write((char*)&stud[i],sizeof(stud[i]));
	outfile.close( );
}

void readstu()
{
	student stud[3];
	int i;
	ifstream infile("stud.dat",ios::binary);
	if(!infile)
	{
		cerr<<"open error!"<<endl;
		exit(1);
	}
	for(i=0;i<3;i++)
		infile.read((char*)&stud[i],sizeof(stud[i]));
	infile.close( );
	for(i=0;i<3;i++)
	{
		cout<<"NO."<<i+1<<endl;
		cout<<"name:"<<stud[i].name<<endl;
		cout<<"num:"<<stud[i].num<<endl;;
		cout<<"age:"<<stud[i].age<<endl;
		cout<<"sex:"<<stud[i].sex<<endl<<endl;
	}
}

//格式化方式从文本文件读取数据 C版
void FormatRead()
{
	int a,b,c;
	FILE *fp=fopen("1.txt","r");
	while(!feof(fp))
	{
		fscanf(fp,"%d,%d,%d",&a,&b,&c);//将文件中的1,2,3中的数字读到a b c中
		cout<<a<<" "<<b<<" "<<c<<endl;
	}
}


//格式化方式从文本文件读取数据 C++版

int main()
{
//	readbyline();
//	writefilebystream();
//	readfilebystream();
//	readbychar();
//	writebychar();

	//二进制文件
//	writebinary();
//	readbinary();
//	writestu();
	//readstu();


	//格式化读取文本文件 C版
	FormatRead();

	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
引用\[1\]提供了一个C语言的例子,展示了如何使用fopen函数来打开文件。在C++中,可以使用fstream库来进行文件操作。fstream库提供了ifstream、ofstream和fstream三个类,分别用于读取文件、写入文件和读写文件。要打开文件,可以使用成员函数open(),并指定文件名和打开模式作为参数。打开模式可以是in(读取)、out(写入)或app(追加),也可以与binary(二进制)组合使用。例如,要以只读方式打开一个文本文件,可以使用以下代码: ```cpp #include <fstream> using namespace std; int main() { ifstream file; file.open("filename.txt", ios::in); if (!file) { cout << "Cannot open file!" << endl; return 1; } // 文件操作代码 file.close(); return 0; } ``` 引用\[2\]提供了一些打开文件时可以使用的模式。例如,"r"表示只读方式打开文件,"w"表示只写方式打开文件(如果文件不存在,则创建一个新文件),"a"表示以追加方式打开文件。可以根据需要选择适合的模式。 请注意,C++中的文件操作与C语言中的略有不同。在C++中,可以使用fstream库提供的类和成员函数来进行文件操作。 #### 引用[.reference_title] - *1* *2* [C++文件操作:fopen / fread / fwrite](https://blog.csdn.net/shenziheng1/article/details/79472102)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [fopen c++打开文件](https://blog.csdn.net/jiangxinyu/article/details/7568082)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值