首页 > 编程语言 >c++文件基本操作

c++文件基本操作

时间:2023-01-02 21:45:47浏览次数:43  
标签:fp 文件 -- ios c++ int 基本操作 open

c++:文件操作全解

文本文件操作

读文件

类别 作用
ios::in 打开一个文件用于读取
ios::out 打开一个文件用于写入
ios::binary 用二进制打开一个文件
ios::app 将文件打开并将文件指针指向文件末尾

这些关键词可以通过 “|” 来并列使用.

#include<ifstream>
#include<iostream>
using namespace std;
int main(){
   ifstream fp;
	fp.open("C:\\Users\\32709\\Desktop\\新建文本文档.txt", ios::in);
	if (!fp.is_open()) {//这个一定要有
		cout << "打开不成功" << endl;
	}
	while (1) {
		string a;
		fp >> a;//遇到空白字符或制表符停止读取
		cout <<"--" <<a<<"--"<<endl;
		if (a == "") {
			break;
		}
	}
    return 0;
}

新建文本文档内容:

我 是 你 的

运行内容:

--我--
--是--
--你--
--的--

写文件

写文件使用ofstream类

#include<ifstream>
#include<iostream>
using namespace std;
int main(){
   ofstream fp;
	fp.open("C:\\Users\\32709\\Desktop\\新建文本文档 (2).txt", ios::out);//打开文件
	if (!fp.is_open()) {
		cout << "打开不成功" << endl;
	}
	string a="我是你的";
	fp << a;//写入文件
    return 0;
}

读/写文件类

fstream 是一个即可当做ofstream来用又可以当做ifstream来用的类,但在实际编程开发中不是用它,因为它的语义不明,并且容易出错

二进制文件操作

在我们现在互联网上有各式各样的文件类型,如jpg、png、MP4等等,这些文件类型本质上都是二进制文件类型,所以学会了对二进制文件的操作就知道这些图片、音频为什么是以这些格式打开的了。

写操作

先来设计一个类

class student{
private:
   int age;//年龄
   char name[20];//名字
   char id[20];//学号
public:
    student(int age,string name,string id){
        this->age=age;
        strcpy(this->name,name.c_Str());
        strcpy(this->id,id.c_Str());
    }
    student(){}
    void disp() {
		cout << name << "\t" << age << "\t" << id << endl;
	}
   
};

我们设计类成员的时候一定要避免使用string类,一但使用string类,当在读取文件时会出现内存泄露的危险。我们要使用字符串时,可以使用字符数组

我们二进制的写操作和文本文件的一样都使用ofstream,但模式变为 ios::binary | ios::out:

int main(){
    student p(12, "张三", "2110901");
	student p1(13, "李四", "2110901");
    
	ofstream fp;
	fp.open("students.txt", ios::binary | ios::out);
    
    //打开文件的检查代码一定要有
	if (fp.is_open()) {
		cout << "打开成功" << endl;
	}
	else {
		cout << "失败\n";
	}
    
    //将两个student类对象写入文件student.txt中
	fp.write((const char*)&p, sizeof(student));//注意要将student*强制转换为const char*
	fp.write((const char*)&p1, sizeof(student));
    fp.close();
    return 0;
}

读文件

我们将对象写入文件,那我们现在讲对象读出文件试试

int main(){
    ifstream fp;
	fp.open("students.txt", ios::binary | ios::in);
	if (fp.is_open()) {
		cout << "打开成功" << endl;
	}
	else {
		cout << "失败\n";
	}
	student temp;
	fp.read((char*)&temp, sizeof(student));
	temp.disp();

	fp.close();
    return 0;
}

结果:

张三 12 2110901

文件指针

在进行某些操作是需要对文件的某一块进行重复扫描,这时我们就要对文件的指针进行操作

tellg();//返回一个整型值,显示文件指针在何处
int num;
seekg(num);//将指针调至文件num字节处    

标签:fp,文件,--,ios,c++,int,基本操作,open
From: https://www.cnblogs.com/Jack-YWJ/p/17020593.html

相关文章