File operations in C++

1.C++ file operations

  File operation header file in C++: fstream.
  File types: file files and binary files.

  • Three major categories of file operations:
        ofstream write operation
        ifstream read operation
        fstream: read and write operations
  • File opening method:
logo illustrate
ios::in read only
ios::out Write only, if the file does not exist, it will be created, if it exists, it will be opened and the original content will be truncated.
ios::ate Open an existing file and point the file read pointer to the end of the file. If the file does not exist, an error will occur.
ios::app Open the file, add content from the end of the file, create the file if it does not exist
ios::trunk Opening the file will truncate the original content, which is the same as ios::out when used alone.
ios::binary Open in binary mode
ios::in|ios::out Open the file, which can be read or written. The original content remains unchanged when the file is opened. If it does not exist, an opening error will occur.
ios::in|ios::out|ios::trunc Open the file, which can be read and written. The original content will be truncated. If the file does not exist, it will be created.

2. Text writing example

#include < iostream >
#include < fstream >
using namespace std;
int main()
{
    
    
	/*1.创建文件*/
	ofstream fp;
	fp.open("test.txt",ios::out);//创建文件,会截断原内容
	if (!fp.is_open())//文件打开失败返回false
	{
    
    
		cout << "文件打开失败!" << endl;
		return 0;
	}
	fp << "C++文件操作示例!" << endl;
	fp << "写入数据测试" << endl;
	fp << "姓名:IT_阿水" << "t工作方向:" << "嵌入式开发" << "t工作时间:" << "6年" << endl;
	fp.close();//关闭文件
	system("pause");
}

3. Text reading example

  There are many ways to read data in C++.

2.1 Example 1: Overload >> Read

#include < iostream >
#include < fstream >
using namespace std;
int main()
{
    
    
	ifstream ifs;
	ifs.open("test.txt",ios::in);//只读方式打开
	if (!ifs.is_open())
	{
    
    
		cout << "文件打开失败!" << endl;
		return 0;
	}
	string str;
	while (ifs >> str)//以字符串方式读取
	{
    
    
		cout << "str=" << str << endl;;
	}
	//关闭文件
	ifs.close();
	system("pause");
}

2.2 Use the member function getline to read

#include < iostream >
#include < fstream >
using namespace std;
int main()
{
    
    
	ifstream ifs;
	ifs.open("test.txt",ios::in);//只读方式打开
	if (!ifs.is_open())
	{
    
    
		cout << "文件打开失败!" << endl;
		return 0;
	}
	//第二种:getline()
	char buff[1024];
	while (ifs.getline(buff, sizeof(buff)))
	{
    
    
		cout << "buff=" << buff << endl;
	}
	//关闭文件
	ifs.close();
	system("pause");
}

2.3 Single character reading get()

#include < iostream >
#include < fstream >
using namespace std;
int main()
{
    
    
	ifstream ifs;
	ifs.open("test.txt",ios::in);//只读方式打开
	if (!ifs.is_open())
	{
    
    
		cout << "文件打开失败!" << endl;
		return 0;
	}
	//第三种:单个字符方式读取
	char c;
	while ((c = ifs.get()) != EOF)
	{
    
    
		cout << c;
	}
	//关闭文件
	ifs.close();
	system("pause");
}

4. Binary mode reading and writing examples

  • Write binary data to file
函数:write(const _Elem* _Str, streamsize _Count)
 形参:_Str --写入的内容的起始地址
       _Count  --写入的字节数
  • Binary data reading file
read(_Elem* _Str, streamsize _Count) ;
 形参:_Str --读取内容存放缓冲区
       _Count --要读取的字节数
#include < iostream >
#include < fstream >
#include < cstring >
using namespace std;
class Person
{
    
    
public:
	Person() {
    
    }
	Person(const char* name, int age)
	{
    
    
		strcpy_s(this->name, name);
		this->age = age;
	}
	char name[20];//姓名
	int age;//年龄
};
int main()
{
    
    
	/*二进制写入数据示例*/
	fstream fs("test.doc", ios::out | ios::binary);
	if (!fs.is_open())
	{
    
    
		cout << "文件创建失败" << endl;
		return 0;
	}
	Person p("小王", 18);
	fs.write((const char *) & p, sizeof(p));//写入内容
	fs.close();//关闭文件
	/*二进制读取数据示例*/
	fs.open("test.doc", ios::in | ios::binary);
	if (!fs.is_open())
	{
    
    
		cout << "文件打开失败" << endl;
		return 0;
	}
	Person p2;
	fs.read((char *) & p2, sizeof(p2));
	cout << "读取的内容:" << endl;
	cout << "姓名:" << p2.name < < "t年龄:" << p2.age << endl;
	fs.close();
	system("pause");

}

5.C++ file pointer offset

//C++文件指针偏移
  seekg(pos_type _Pos,ios_base::seekdir _Way)  --用于输入流,偏移位置指针到指定位置
  seekp(pos_type _Pos,ios_base::seekdir _Way)  --用于输出流,偏移位置指针到指定位置
	第一个参数:偏移量
	第二个参数:基于哪个位置
				ios::beg  --文件头
				ios::end  --文件尾
				ios::cur  --当前位置
  streamoff tellg()  --用于输入流,返回当前指针位置,streamoff 是一个long long类型
  streamoff tellp()  --用于输出流,返回当前指针位置
  返回值返回基于文件头的偏移量,字节为单位。失败则返回-1
  • Example:
#include < iostream >
#include < fstream >
using namespace std;
int main()
{
    
    
	ifstream fs;
	fs.open("test.txt", ios::in );//打开文件,不存在则打开失败,不会截断原内容
	if (!fs.is_open())
	{
    
    
		cout << "文件打开失败" << endl;
		return 0;
	}
	fs.seekg(0,ios::end);//将文件指针偏移到文件末尾
	char buff[1024];
	streamoff  size = fs.tellg();//获取文件大小
	cout << "文件大小:" << size << "字节" << endl;
	fs.seekg(0, ios::beg);//将输入流偏移到文件头
	while (fs >> buff)
	{
    
    
		cout << buff << endl;
	}
	fs.close();
	system("pause");
	return 0;
}

Insert image description here

Guess you like

Origin blog.csdn.net/weixin_44453694/article/details/131912583