cpp►结构体IO

Posted itzyjr

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cpp►结构体IO相关的知识,希望对你有一定的参考价值。

写入结构体到文件:

#include <iostream>
#include <fstream>
#include <string>
#include <cctype> // for toupper
using namespace std;
const int NAME_SIZE = 51;
struct Info {
	char name[NAME_SIZE];
	int age;
};
int main() {
	Info person; // store information about a person
	char response; // user response
	string input; // used to read strings
	// create file object and open file, in binary mode
	fstream people("people.dat", ios::out | ios::binary);
	if (!people) {
		cout << "Error opening file. Program aborting.\\n";
		return 0;
	}
	// Keep getting information from user and writing it to the file in binary mode
	do {
		cout << "Enter person information:\\n";
		cout << "Name: ";
		getline(cin, input);
		strcpy(person.name, input.c_str());
		cout << "Age: ";
		cin >> person.age;
		cin.ignore();// skip over remaining newline

		people.write(reinterpret_cast<char*>(&person), sizeof(person));
		cout << "Do you want to enter another record? ";
		cin >> response;
		cin.ignore();
	} while (toupper(response) == 'Y');
	people.close();// close file
	return 0;
}

第一个实参是 person 变量的地址。reinterpret_cast<char*> 转换操作符是必需的,因为 write 需要第一个实参是一个指向 char 的指针。如果将除 char 之外的其他任何东西的地址传递给 write 函数,则必须使用转换操作符使它看起来像是一个指向 char 的指针。第二个实参是 sizeof 运算符,它告诉 write 有多少个字节要写入文件。

Enter person information:
Name: |akuan<Enter>
Age: |32<Enter>
Do you want to enter another record? |Y<Enter>
Enter person information:
Name: |jack<Enter>
Age: |21<Enter>
Do you want to enter another record? |N<Enter>

在工程根目录下生成people.dat,如下:

从文件读取结构体:

// read a struct of information from a file.
#include <iostream>
#include <fstream>
using namespace std;
const int NAME_SIZE = 51;
struct Info {
	char name[NAME_SIZE];
	int age;
};
int main() {
	Info person;
	char response;
	// create file object and open file for binary reading
	fstream people("people.dat", ios::in | ios::binary);
	if (!people) {
		cout << "Error opening file. Program aborting.\\n";
		return 0;
	}
	cout << "###Below are the people in the file###\\n";
	people.read(reinterpret_cast<char*>(&person), sizeof(person));
	while (!people.eof()) {
		cout << "Name: ";
		cout << person.name << endl;
		cout << "Age: ";
		cout << person.age << endl;
		cout << "\\nStrike any key to see the next record.\\n";
		cin.get(response);
		people.read(reinterpret_cast<char*>(&person), sizeof(person));
	}
	cout << "That's all the information in the file!\\n";
	people.close();
	return 0;
}
###Below are the people in the file###
Name: akuan
Age: 32

Strike any key to see the next record.
|<Enter>
Name: jack
Age: 21

Strike any key to see the next record.
|<Enter>
That's all the information in the file!

以上是关于cpp►结构体IO的主要内容,如果未能解决你的问题,请参考以下文章

分享几个实用的代码片段(第二弹)

分享几个实用的代码片段(第二弹)

c++中如何跨cpp文件调用结构体变量

C语言编程 结构体让多个CPP使用

c_cpp 初始化结构体#结构体

C++创建一个结构体应该放在.cpp文件中吗?然后调用的时候只要包含这个.cpp文件?