操作系统实验——设置简单的文件系统(C++)

要求:设置一个简单的文件系统,其实现了创建文件,打开文件,删除文件,关闭文件,读文件和写文件等一系列简单操作

源代码:

#include<fstream>
#include<iostream>
#include<vector>
//#include<windows.h>
using namespace std;
void CreatFile()
{
	string filename;
	cout << "请输入所要创建的文件名:";
	cin >> filename;
	fstream outstuf;
	outstuf.open(filename, ios::out);//连接文件
	if (!outstuf)
	{
		cerr << "文件创建失败!" << endl;
		return;
	}
	cout << "创建成功!\n";
	outstuf.close();
}
void Open()
{
	string filename;
	cout << "请输入所要打开的文件名:";
	cin >> filename;
	ifstream outstuf;
	outstuf.open(filename, ios::in);//以只读的方式打开
	if (!outstuf.is_open())
	{
		cerr << "该文件不存在,打开失败!" << endl;
		return;
	}
	cout << "文件已打开!";
	outstuf.close();
}
void Read()
{
	string filename;
	char s[100];
	cout << "请输入所要打开的文件名:";
	cin >> filename;
	ifstream instuf(filename, ios::in);
	instuf.seekg(0, ios::beg);//流指针置在文件头
	if (!instuf)
	{
		cerr << "文件不能打开,读取失败!" << endl;
		return;
	}
	else if (instuf.eof())
		cout << "该文件为空!";
	while (!instuf.eof())
	{
		instuf.getline(s, 100);
		cout << s << endl;
	}
	instuf.close();
}
void Write()
{
	string filename;
	string s;
	cout << "请输入所要写入的文件名:";
	cin >> filename;
	ifstream instuf(filename, ios::in);
	if (!instuf.is_open())
	{
		cerr<<"文件打不开,写入失败!\n";
		return;
	}
	ofstream outstuf(filename, ios::out);
	cin >> s;
	cin.ignore(1024, '\n');//清空整个缓冲区
	outstuf << s;
	instuf.close();
	outstuf.close();
}
	
void Delet()
{
	string filename;
	cout << "请输入所要删除的文件名:";
	cin >> filename;
	const char* FileName = filename.c_str();
	if (remove(FileName) == 0)
	{
		cout << "删除成功!" << endl;
	}
	else
		cout << "删除失败!" << endl;

}
int main()
{
	int command;
	bool running = true;
	cout.fill('*');
	cout.width(25);
	cout << "文件系统";
	cout.fill('*');
	cout.width(20);
	cout << "\n";
	cout << "\t1.创建文件\t2.删除文件\n\t3.读文件\t4.写文件\n\t5.打开文件\t0.退出\n\n\n";
	while (running)
	{

		cout << "请输入指令:";
		cin >> command;
		switch (command)
		{
		case 1:
			CreatFile(); break;
		case 2:
			Delet(); break;
		case 3:
			Read(); break;
		case 4:
			Write(); break;
		case 5:
			Open(); break;
		case 0:
			running = false; break;
		default:
			cout << "输入错误!请重新输入" << endl; break;
		}
	}
	return 0;
}

运行结果:

设计流程图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值