操作系统实验文件管理C++代码

合集下载

C#资源(文件)管理器 实验报告

C#资源(文件)管理器 实验报告

实验5 文件管理器【实验目的】⏹进一步实践windows窗口程序开发的流程;⏹掌握并熟练使用后台代码添加控件并定义布局和格式以及交互的技能。

【实验环境】Visual Studio 2005(或更高版本)【实验内容】设计一个基于后台代码添加控件的方式来实现文件管理器的显示和交互功能的Winform程序,鼓励扩展其他功能。

基本功能如下图:【实验记录】文件菜单:新建文件夹:提供即时重命名新建文件夹遇到相同明添加序号新建文本文档新建文本文档遇到相同明添加序号选中单个项目激活重命名和删除选中多个项目禁用重命名编辑菜单:(撤销功能未完成)选择项目激活剪切和复制状态栏显示选择项信息点击复制或剪切激活复制在同目录下黏贴同名添加“- 副本”点击全选查看菜单:点击状态栏默认打开点击后关闭点击大图标:点击小图标点击详细信息排序方式类型点击列头同样实现排序方式递减转至:前进禁用点击后退前进启用点击前进点击向上一级:向上到磁盘跟目录禁用向上一级帮助关于:工具栏与菜单栏选定状态同步功能相同右键菜单:启用状态与菜单栏工具栏同步功能相同本软件提供单项(多项未完成请勿测试)拖拽移动项目无法截图展示请自行测试【核心代码】using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Windows.Forms;using System.Security.AccessControl;using Microsoft.Win32;using System.IO;using System.Collections;namespace FileExplorer{public partial class Form1 : Form{static DirectoryInfo currentDir;string[] newpath = new string[1024];string[] oldpath = new string[1024];string[] type = new string[1024];List<string> ls = new List<string>();int ind;ListViewItemSorter sorter;public Form1(){InitializeComponent();sorter = new ListViewItemSorter();listView1.ListViewItemSorter = sorter;sorter.SortColumn = 0;sorter.SortOrder = SortOrder.Ascending;}private void Form1_Load(object sender, EventArgs e){getDisks();toolStripStatusLabel1.Text = DateTime.Now.ToString();}private void getDisks(){foreach (DriveInfo d in DriveInfo.GetDrives()){if (d.IsReady){TreeNode root = new TreeNode();root.Tag = ;treeView1.Nodes.Add(root);getAll(root);}}}private void getAll(TreeNode parentNode){#regionDirectoryInfo parentDir = new DirectoryInfo(parentNode.FullPath);DirectorySecurity s = new DirectorySecurity(parentNode.FullPath, AccessControlSections.Access);if (!s.AreAccessRulesProtected){if (parentDir.GetDirectories() != null){foreach (DirectoryInfo childDir in parentDir.GetDirectories()){TreeNode childNode = new TreeNode();childNode.Tag = childDir.FullName;parentNode.Nodes.Add(childNode);// getAll(childNode);}}}#endregion// #region// DirectoryInfo directory;// try// {// // 第一层路径// if (parentNode.Nodes.Count == 0)// {// directory = new DirectoryInfo(parentNode.FullPath);// foreach (DirectoryInfo dir in directory.GetDirectories())// {// TreeNode newNode = new TreeNode();// parentNode.Nodes.Add(newNode);// }// }// // 第二层路径// foreach (TreeNode node in parentNode.Nodes)// {// if (node.Nodes.Count == 0)// {// directory = new DirectoryInfo(node.FullPath);// foreach (DirectoryInfo dir in directory.GetDirectories())// {// TreeNode newNode = new TreeNode();// node.Nodes.Add(newNode);// }// }// }// }// catch (Exception doh)// {// Console.WriteLine(doh.Message);// }//#endregion}private void showListView(string path){this.listView1.Items.Clear();currentDir = new DirectoryInfo(path);DirectorySecurity s = new DirectorySecurity(path, AccessControlSections.Access);if (!s.AreAccessRulesProtected){if (currentDir.GetDirectories() != null){foreach (DirectoryInfo dir in currentDir.GetDirectories()){ListViewItem item = new ListViewItem();//this.imageList2.Images.Add(System.Drawing.Icon.FromHandle(dir.FullName));//FileAttributesitem.SubItems.Add("");item.SubItems.Add("文件夹");item.SubItems.Add(File.GetCreationTime(dir.FullName).ToString("u"));item.SubItems.Add(File.GetLastWriteTime(dir.FullName).ToString("u"));item.SubItems.Add(File.GetLastAccessTime(dir.FullName).ToString("u"));item.Tag = "0";item.ToolTipText = dir.FullName;item.ImageIndex = 0;//item.ImageIndex = this.imageList2.Images.Count - 1;this.listView1.Items.Add(item);}foreach (FileInfo file in currentDir.GetFiles()){ListViewItem item = new ListViewItem();item.SubItems.Add(file.Length<1024*1024?""+file.Length/1024+"KB":""+file.Length/1024/1024+" MB");item.SubItems.Add(checkFileType(file.FullName));item.SubItems.Add(File.GetCreationTime(file.FullName).ToString("u"));item.SubItems.Add(File.GetLastWriteTime(file.FullName).ToString("u"));item.SubItems.Add(File.GetLastAccessTime(file.FullName).ToString("u"));//if(!this.imageList1.Images.ContainsKey(Path.GetExtension()))//{// this.imageList1.Images.Add(Path.GetExtension(), System.Drawing.Icon.ExtractAssociatedIcon(file.FullName));//}this.imageList2.Images.Add(System.Drawing.Icon.ExtractAssociatedIcon(file.FullName));this.imageList3.Images.Add(System.Drawing.Icon.ExtractAssociatedIcon(file.FullName));this.imageList4.Images.Add(System.Drawing.Icon.ExtractAssociatedIcon(file.FullName));this.imageList5.Images.Add(System.Drawing.Icon.ExtractAssociatedIcon(file.FullName));item.Tag = "1";item.ToolTipText = file.FullName;if(this.listView1.View==rgeIcon)item.ImageIndex = this.imageList2.Images.Count - 1;if (this.listView1.View == rgeIcon)item.ImageIndex = this.imageList2.Images.Count - 1;if (this.listView1.View == View.SmallIcon)item.ImageIndex = this.imageList3.Images.Count - 1;if (this.listView1.View == View.List)item.ImageIndex = this.imageList4.Images.Count - 1;if (this.listView1.View == View.Details)item.ImageIndex = this.imageList5.Images.Count - 1;// item.ImageIndex = this.imageList1.Images.IndexOfKey(Path.GetExtension());;this.listView1.Items.Add(item);}}}toolStripStatusLabel2.Text ="\n"+listView1.Items.Count + "个项目";}private string checkFileType(string path){string ext = Path.GetExtension(path);try{string desc = (string)Registry.ClassesRoot.OpenSubKey(ext).GetValue(null);return (string)Registry.ClassesRoot.OpenSubKey(desc).GetValue(null);}catch (NullReferenceException nre) {return "不可识别的文件类型";}}private void treeView1_AfterSelect(object sender, TreeViewEventArgs e){getAll(e.Node); // 取得选择节点的子文件夹addressTB.Text = e.Node.FullPath; // 更新文本框内容currentDir = new DirectoryInfo(e.Node.FullPath);showListView(e.Node.FullPath);if (currentDir.Parent != null){toolStripButton1.Enabled = true;向上一级ToolStripMenuItem.Enabled = true;}ls.Add(addressTB.Text);ind = ls.Count - 1;}private void listView1_DoubleClick(object sender, EventArgs e){foreach (ListViewItem item in this.listView1.SelectedItems){if (item.Tag.ToString() == "0"){showListView(item.ToolTipText);addressTB.Text = item.ToolTipText;ls.Add(addressTB.Text);ind = ls.Count-1;}if (item.Tag.ToString() == "1"){try { System.Diagnostics.Process.Start(item.ToolTipText); }catch (Win32Exception w32e){MessageBox.Show("亲,对不起,系统没能找到合适的程序打开该文件哦!");}}}if (currentDir.Parent != null){toolStripButton1.Enabled = true;向上一级ToolStripMenuItem.Enabled = true;}}private void toolStripButton2_Click(object sender, EventArgs e){后退ToolStripMenuItem_Click(sender, e);}private void 大图标ToolStripMenuItem_Click(object sender, EventArgs e){viewcheck();大图标CToolStripMenuItem.Checked = true;大图标ToolStripMenuItem.Checked = true;this.listView1.View = rgeIcon;}private void 小图标ToolStripMenuItem_Click(object sender, EventArgs e){viewcheck();小图标OToolStripMenuItem.Checked = true;小图标ToolStripMenuItem.Checked = true;this.listView1.View = View.SmallIcon;}private void 列表ToolStripMenuItem_Click(object sender, EventArgs e){viewcheck();列表ToolStripMenuItem1.Checked = true;列表ToolStripMenuItem.Checked = true;this.listView1.View = View.List;}private void 详细信息ToolStripMenuItem_Click(object sender, EventArgs e){viewcheck();详细信息ToolStripMenuItem.Checked = true;详细信息ToolStripMenuItem1.Checked = true;this.listView1.View = View.Details;}private void Form1_SizeChanged(object sender, EventArgs e){this.treeView1.Width = this.Width * 24 / 100;this.listView1.Width = this.Width -this.treeView1.Width-10;}private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)//重命名后判断是否存在同名{string temp = listView1.SelectedItems[0].Text;e.CancelEdit = false;if (bel == null)//取消重命名则退出编辑e.CancelEdit = true;else{if (Directory.Exists(currentDir.FullName + "\\" + bel)){MessageBox.Show("此目标已包含名为\"" + bel + "\"", "重命名失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);e.CancelEdit = true;//同名则自动取消重命名恢复原有命名}else{Directory.Move(currentDir.FullName + "\\" + temp, currentDir.FullName + "\\" + bel);}}}private void 文件夹ToolStripMenuItem_Click(object sender, EventArgs e){string path = currentDir.FullName + "\\新建文件夹";path = directorynum(path);Directory.CreateDirectory(path);ListViewItem item = new ListViewItem(path.Substring(stIndexOf('\\') + 1));//添加listview的项item.SubItems.Add("");item.SubItems.Add("文件夹");item.SubItems.Add(File.GetCreationTime(path).ToString("u"));item.SubItems.Add(File.GetLastWriteTime(path).ToString("u"));item.SubItems.Add(File.GetLastAccessTime(path).ToString("u"));item.Tag = "0";item.ToolTipText = path;item.ImageIndex = 0;this.listView1.Items.Add(item);item.EnsureVisible();//滚动条到可见新建的文件夹item.BeginEdit();//新建完提供即时重命名}private void 文件ToolStripMenuItem_Click(object sender, EventArgs e){string path = currentDir.FullName + "\\新建文本文档.txt";path = filenum(path);File.CreateText(path);ListViewItem item = new ListViewItem(path.Substring(stIndexOf('\\') + 1));item.SubItems.Add(path.Length < 1024 * 1024 ? "" + path.Length / 1024 + "KB" : "" + path.Length / 1024 / 1024 + "MB");item.SubItems.Add(checkFileType(path));item.SubItems.Add(File.GetCreationTime(path).ToString("u"));item.SubItems.Add(File.GetLastWriteTime(path).ToString("u"));item.SubItems.Add(File.GetLastAccessTime(path).ToString("u"));item.Tag = "1";item.ToolTipText = path;this.listView1.Items.Add(item);item.EnsureVisible();item.BeginEdit();}private void 重命名MToolStripMenuItem_Click(object sender, EventArgs e) {listView1.SelectedItems[0].BeginEdit();}private void 文件夹FToolStripMenuItem_Click(object sender, EventArgs e) {文件夹ToolStripMenuItem_Click(sender, e);}private void 文本文档ToolStripMenuItem_Click(object sender, EventArgs e) {文件ToolStripMenuItem_Click(sender,e);}private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) {if (listView1.SelectedItems.Count == 1){重命名MToolStripMenuItem1.Enabled = true;删除DToolStripMenuItem.Enabled = true;剪切CToolStripMenuItem.Enabled = true;复制CToolStripMenuItem1.Enabled = true;}if (listView1.SelectedItems.Count > 1){删除DToolStripMenuItem.Enabled = true;剪切CToolStripMenuItem.Enabled = true;复制CToolStripMenuItem1.Enabled = true;重命名MToolStripMenuItem1.Enabled = false;}if (listView1.SelectedItems.Count == 0){剪切CToolStripMenuItem.Enabled = false;复制CToolStripMenuItem1.Enabled = false;重命名MToolStripMenuItem1.Enabled = false;删除DToolStripMenuItem.Enabled = false;}}private void 文件FToolStripMenuItem_Click(object sender, EventArgs e) {if (listView1.SelectedItems.Count == 1){重命名MToolStripMenuItem.Enabled = true;删除ToolStripMenuItem.Enabled = true;}if (listView1.SelectedItems.Count > 1){删除ToolStripMenuItem.Enabled = true;重命名MToolStripMenuItem.Enabled = false;}if (listView1.SelectedItems.Count == 0){重命名MToolStripMenuItem.Enabled = false;删除ToolStripMenuItem.Enabled = false;}}private void 重命名MToolStripMenuItem1_Click(object sender, EventArgs e){重命名MToolStripMenuItem_Click(sender, e);}private void 新建NToolStripButton_Click(object sender, EventArgs e){文件ToolStripMenuItem_Click(sender, e);}private void 删除ToolStripMenuItem_Click(object sender, EventArgs e){DialogResult result = MessageBox.Show("确定要删除吗?", "确认删除", MessageBoxButtons.YesNo, rmation);if (result == DialogResult.Yes){foreach (ListViewItem temp in listView1.SelectedItems){if (temp.SubItems[1].Text.Equals(""))//判断所要删除的是文件或文件夹Directory.Delete(currentDir.FullName + "\\" + temp.Text, true);elseFile.Delete(currentDir.FullName + "\\" + temp.Text);temp.Remove();}}}private void 删除DToolStripMenuItem_Click(object sender, EventArgs e){删除ToolStripMenuItem_Click(sender, e);}private void CopyDirectory(string sourceDirName, string destDirName){if (sourceDirName.Substring(sourceDirName.Length - 1) != "\\"){sourceDirName = sourceDirName + "\\";//截取出源文件夹目录}if (destDirName.Substring(destDirName.Length - 1) != "\\"){destDirName = destDirName + "\\";//截取出目标文件夹目录}Directory.CreateDirectory(destDirName);//复制文件夹下的子文件夹foreach (string item in Directory.GetFiles(sourceDirName))//复制文件夹下的文件{File.Copy(item, destDirName + Path.GetFileName(item), true);}foreach (string item in Directory.GetDirectories(sourceDirName)){sourceDirName = item;destDirName = destDirName.Substring(0, stIndexOf("\\") + 1) + item.Substring(stIndexOf("\\") + 1);CopyDirectory(sourceDirName, destDirName);//递归完成文件夹下子文件夹和文件复制}}private void 复制CToolStripMenuItem_Click(object sender, EventArgs e){oldpath[0] = "复制";//设置标记复制或剪切type[0] = "";int i = 1;foreach (ListViewItem temp in listView1.SelectedItems){oldpath[i] = currentDir.FullName + "\\" + temp.Text;//存储源路径if (temp.SubItems[1].Text.Equals(""))//存储源类型以便后续操作type[i] = "文件夹";elsetype[i] = "文件";i++;}粘贴PToolStripButton.Enabled = true;粘贴PToolStripMenuItem.Enabled = true;粘贴PToolStripMenuItem1.Enabled = true;}private void 剪切TToolStripMenuItem_Click(object sender, EventArgs e){oldpath[0] = "剪切";type[0] = "";int i = 1;foreach (ListViewItem temp in listView1.SelectedItems){oldpath[i] = currentDir.FullName + "\\" + temp.Text;if (temp.SubItems[1].Text.Equals(""))type[i] = "文件夹";elsetype[i] = "文件";i++;}粘贴PToolStripButton.Enabled = true;粘贴PToolStripMenuItem.Enabled = true;粘贴PToolStripMenuItem1.Enabled = true;}private void 粘贴PToolStripMenuItem_Click(object sender, EventArgs e){if (oldpath[0].Equals("复制")){for (int i = 1; i < oldpath.Length; i++){if (oldpath[i] == null)//路径为空后停止黏贴break;newpath[i] = currentDir.FullName + oldpath[i].Substring(oldpath[i].LastIndexOf('\\')+1);//设置新路径名if (type[i].Equals("文件夹")){if (Directory.Exists(newpath[i]))//判断目标目录下是否有同名文件newpath[i] = newpath[i] + " - 副本";newpath[i] = directorynum(newpath[i]);CopyDirectory(oldpath[i], newpath[i]);}else{if (File.Exists(newpath[i]))//判断目标目录下是否有同名文件newpath[i] = newpath[i].Insert(newpath[i].LastIndexOf("."), " - 副本");newpath[i] = filenum(newpath[i]);File.Copy(oldpath[i], newpath[i]);}}}if (oldpath[0].Equals("剪切")){for (int i = 1; i < oldpath.Length; i++){if (oldpath[i] == null)break;newpath[i] = currentDir.FullName + oldpath[i].Substring(oldpath[i].LastIndexOf('\\') + 1);if (type[i].Equals("文件夹")){if (Directory.Exists(newpath[i]))//判断目标目录下是否有同名文件newpath[i] = newpath[i] + " - 副本";newpath[i] = directorynum(newpath[i]);CopyDirectory(oldpath[i], newpath[i]);Directory.Delete(oldpath[i], true);}else{if(File.Exists(newpath[i]))//判断目标目录下是否有同名文件newpath[i] = newpath[i].Insert(newpath[i].Length - 4, " - 副本");newpath[i] = filenum(newpath[i]);File.Move(oldpath[i], newpath[i]);}}}for (int i = 1; i < oldpath.Length; i++)//添加listview的项{if (newpath[i] == null)break;if (type[i].Equals("文件夹")){ListViewItem item = new ListViewItem(newpath[i].Substring(newpath[i].LastIndexOf('\\') + 1));item.SubItems.Add("");item.SubItems.Add("文件夹");item.SubItems.Add(File.GetCreationTime(newpath[i]).ToString("u"));item.SubItems.Add(File.GetLastWriteTime(newpath[i]).ToString("u"));item.SubItems.Add(File.GetLastAccessTime(newpath[i]).ToString("u"));item.Tag = "0";item.ToolTipText = newpath[i];item.ImageIndex = 0;this.listView1.Items.Add(item);}else{ListViewItem item = new ListViewItem(newpath[i].Substring(newpath[i].LastIndexOf('\\') + 1));item.SubItems.Add(newpath[i].Length < 1024 * 1024 ? "" + newpath[i].Length / 1024 + "KB" : "" + newpath[i].Length / 1024 / 1024 + "MB");item.SubItems.Add(checkFileType(newpath[i]));item.SubItems.Add(File.GetCreationTime(newpath[i]).ToString("u"));item.SubItems.Add(File.GetLastWriteTime(newpath[i]).ToString("u"));item.SubItems.Add(File.GetLastAccessTime(newpath[i]).ToString("u"));item.Tag = "1";item.ToolTipText = newpath[i];this.listView1.Items.Add(item);}}}private void 全选AToolStripMenuItem_Click(object sender, EventArgs e){foreach(ListViewItem temp in listView1.Items)temp.Selected = true;listView1.Focus();}private void 编辑EToolStripMenuItem_Click(object sender, EventArgs e){//判断是否有选定项再启用选项if (listView1.SelectedItems.Count >= 1){剪切TToolStripMenuItem.Enabled = true;复制CToolStripMenuItem.Enabled = true;}if (listView1.SelectedItems.Count == 0){剪切TToolStripMenuItem.Enabled = false;复制CToolStripMenuItem.Enabled = false;}}private void 剪切CToolStripMenuItem_Click(object sender, EventArgs e) {剪切TToolStripMenuItem_Click(sender, e);}private void 复制CToolStripMenuItem1_Click(object sender, EventArgs e) {复制CToolStripMenuItem_Click(sender,e);}private void 粘贴PToolStripMenuItem1_Click(object sender, EventArgs e) {粘贴PToolStripMenuItem_Click(sender, e);}private void 剪切UToolStripButton_Click(object sender, EventArgs e) {剪切TToolStripMenuItem_Click(sender, e);}private void 复制CToolStripButton_Click(object sender, EventArgs e) {复制CToolStripMenuItem_Click(sender, e);}private void 粘贴PToolStripButton_Click(object sender, EventArgs e) {粘贴PToolStripMenuItem_Click(sender, e);}private void viewcheck()//取消所有视图选项{详细信息ToolStripMenuItem.Checked = false;大图标CToolStripMenuItem.Checked = false;小图标OToolStripMenuItem.Checked = false;列表ToolStripMenuItem1.Checked = false;大图标ToolStripMenuItem.Checked = false;小图标ToolStripMenuItem.Checked = false;列表ToolStripMenuItem.Checked = false;详细信息ToolStripMenuItem1.Checked = false;}private void 自定义CToolStripMenuItem_Click(object sender, EventArgs e){viewcheck();大图标ToolStripMenuItem_Click(sender, e);大图标CToolStripMenuItem.Checked = true;大图标ToolStripMenuItem.Checked = true;}private void 选项OToolStripMenuItem_Click(object sender, EventArgs e){viewcheck();this.listView1.View = View.SmallIcon;小图标OToolStripMenuItem.Checked = true;小图标ToolStripMenuItem.Checked = true;}private void 列表ToolStripMenuItem1_Click(object sender, EventArgs e){viewcheck();this.listView1.View = View.List;列表ToolStripMenuItem1.Checked = true;列表ToolStripMenuItem.Checked = true;}private void 详细信息ToolStripMenuItem_Click_1(object sender, EventArgs e) {viewcheck();this.listView1.View = View.Details;详细信息ToolStripMenuItem.Checked = true;详细信息ToolStripMenuItem1.Checked = true;}private void addressTB_TextChanged(object sender, EventArgs e){if (ls.Count > 1)//判断是否能后退在启用后退选项{toolStripButton2.Enabled = true;后退ToolStripMenuItem.Enabled = true;}if (addressTB.Text.EndsWith("\\"))//判断是否能向上一级在启用向上一级选项{toolStripButton1.Enabled = false;向上一级ToolStripMenuItem.Enabled = false;}else{toolStripButton1.Enabled = true;向上一级ToolStripMenuItem.Enabled = true;}}private void 后退ToolStripMenuItem_Click(object sender, EventArgs e) {ind--;showListView(ls[ind]);addressTB.Text = ls[ind];前进ToolStripMenuItem.Enabled = true;toolStripButton3.Enabled = true;if (ind == 0){后退ToolStripMenuItem.Enabled = false;toolStripButton2.Enabled = false;}}private void 前进ToolStripMenuItem_Click(object sender, EventArgs e) {ind++;showListView(ls[ind]);addressTB.Text = ls[ind];if (ind == ls.Count-1){前进ToolStripMenuItem.Enabled = false;toolStripButton3.Enabled = false;}}private void toolStripButton1_Click(object sender, EventArgs e){if (currentDir.Parent != null){ls.Add(currentDir.Parent.FullName);ind = ls.Count - 1;this.addressTB.Text = currentDir.Parent.FullName;showListView(currentDir.Parent.FullName);前进ToolStripMenuItem.Enabled = false;toolStripButton3.Enabled = false;}}private void toolStripButton3_Click(object sender, EventArgs e){前进ToolStripMenuItem_Click(sender, e);}private void 向上一级ToolStripMenuItem_Click(object sender, EventArgs e) {toolStripButton1_Click(sender, e);}private void sortcheck()//取消所有选定项{名称ToolStripMenuItem.Checked = false;大小ToolStripMenuItem.Checked = false;类型ToolStripMenuItem.Checked = false;创建时间ToolStripMenuItem.Checked = false;}private void 名称ToolStripMenuItem_Click(object sender, EventArgs e) {sortcheck();名称ToolStripMenuItem.Checked = true;sorter.SortColumn = 0;listView1.Sort();}private void 大小ToolStripMenuItem_Click(object sender, EventArgs e) {sortcheck();大小ToolStripMenuItem.Checked = true;sorter.SortColumn = 1;listView1.Sort();}private void 类型ToolStripMenuItem_Click(object sender, EventArgs e) {sortcheck();类型ToolStripMenuItem.Checked = true;sorter.SortColumn = 2;listView1.Sort();}private void 创建时间ToolStripMenuItem_Click(object sender, EventArgs e) {sortcheck();创建时间ToolStripMenuItem.Checked = true;sorter.SortColumn = 4;listView1.Sort();}private void 递增ToolStripMenuItem_Click(object sender, EventArgs e) {递增ToolStripMenuItem.Checked = true;递减ToolStripMenuItem.Checked = false;sorter.SortOrder = SortOrder.Ascending;listView1.Sort();}private void 递减ToolStripMenuItem_Click(object sender, EventArgs e) {递增ToolStripMenuItem.Checked = false;递减ToolStripMenuItem.Checked = true;sorter.SortOrder = SortOrder.Descending;listView1.Sort();}private void listView1_ColumnClick(object sender, ColumnClickEventArgs e) {if (e.Column == this.sorter.SortColumn){if (this.sorter.SortOrder == SortOrder.Ascending){this.sorter.SortOrder = SortOrder.Descending;递增ToolStripMenuItem.Checked = false;//同步菜单选项递减ToolStripMenuItem.Checked = true;}elseif (this.sorter.SortOrder == SortOrder.Descending){this.sorter.SortOrder = SortOrder.Ascending;递增ToolStripMenuItem.Checked = true;递减ToolStripMenuItem.Checked = false;}elsereturn;}else{this.sorter.SortColumn = e.Column;}sortcheck();if (e.Column == 0)//同步菜单排序选项名称ToolStripMenuItem.Checked = true;else if (e.Column == 1)大小ToolStripMenuItem.Checked = true;else if (e.Column == 2)类型ToolStripMenuItem.Checked = true;else if (e.Column == 4)创建时间ToolStripMenuItem.Checked = true;listView1.Sort();}private void 关闭ToolStripMenuItem_Click(object sender, EventArgs e){this.Close();}private void listView1_SelectedIndexChanged(object sender, EventArgs e){if (listView1.SelectedItems.Count == 0){toolStripStatusLabel2.Image = null;toolStripStatusLabel2.Text = "\n" + listView1.Items.Count + "个项目";}else if (listView1.SelectedItems.Count == 1){if (listView1.SelectedItems[0].ImageIndex != -1)toolStripStatusLabel2.Image = imageList2.Images[listView1.SelectedItems[0].ImageIndex];toolStripStatusLabel2.Text = listView1.SelectedItems[0].Text + " \n修改日期:" + listView1.SelectedItems[0].SubItems[4].Text;}else{toolStripStatusLabel2.Image = null;toolStripStatusLabel2.Text = "\n已选择" + listView1.SelectedItems.Count + "项";}if (listView1.SelectedIndices.Count !=0){剪切UToolStripButton.Enabled = true;复制CToolStripButton.Enabled = true;}else{剪切UToolStripButton.Enabled = false;复制CToolStripButton.Enabled = false;}}private void timer1_Tick(object sender, EventArgs e){toolStripStatusLabel1.Text = DateTime.Now.ToString();}private void 状态栏ToolStripMenuItem_Click(object sender, EventArgs e) {if (状态栏ToolStripMenuItem.Checked == true){状态栏ToolStripMenuItem.Checked = false;statusStrip2.Visible = false;}else{状态栏ToolStripMenuItem.Checked = true;statusStrip2.Visible = true;}}private string filenum(string filename){string nums = "";int num = 1;while (true)//判断路径下是否已存在文件否则加上序号标签{if (File.Exists(filename.Insert(stIndexOf("."), nums + ""))){num++;nums = "(" + num + ")";}else{filename = filename.Insert(stIndexOf("."), nums + "");break;}}return filename;}private string directorynum(string directoryname){string nums = "";int num = 1;while (true)//判断路径下是否已存在该文件夹否则加上序号标签{if (Directory.Exists(directoryname + nums)){num++;nums = "(" + num + ")";}else{directoryname = directoryname + nums;break;}}return directoryname;}private void 关于AToolStripMenuItem_Click(object sender, EventArgs e){AboutBox1 ab = new AboutBox1();ab.Show();}private void listView1_DragDrop(object sender, DragEventArgs e){ListViewItem draggedItem = (ListViewItem)e.Data.GetData(typeof(ListViewItem));Point ptScreen = new Point(e.X, e.Y);Point pt = listView1.PointToClient(ptScreen);ListViewItem TargetItem = listView1.GetItemAt(pt.X, pt.Y);//拖动的项将放置于该项之前if (TargetItem.ToolTipText.Equals(draggedItem.ToolTipText))return;if (null != TargetItem && TargetItem.Tag.Equals("0")){if (draggedItem.Tag.Equals("0")){if (!Directory.Exists(TargetItem.ToolTipText + "\\" + draggedItem.Text)){CopyDirectory(draggedItem.ToolTipText, TargetItem.ToolTipText + "\\" + draggedItem.Text);Directory.Delete(draggedItem.ToolTipText, true);listView1.Items.Remove(draggedItem);}elseMessageBox.Show("该目录下已存在同名文件夹", "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);}else{if (!File.Exists(TargetItem.ToolTipText + "\\" + draggedItem.Text)){File.Move(draggedItem.ToolTipText, TargetItem.ToolTipText + "\\" + draggedItem.Text);listView1.Items.Remove(draggedItem);}elseMessageBox.Show("该目录下已存在同名文件", "操作失败", MessageBoxButtons.OK, MessageBoxIcon.Warning);}}}private void listView1_DragEnter(object sender, DragEventArgs e){e.Effect = e.AllowedEffect;}private void listView1_ItemDrag(object sender, ItemDragEventArgs e){listView1.DoDragDrop(e.Item, DragDropEffects.Move);}private void listView1_DragOver(object sender, DragEventArgs e){Point ptScreen = new Point(e.X, e.Y);Point pt = listView1.PointToClient(ptScreen);ListViewItem item = listView1.GetItemAt(pt.X, pt.Y);if (listView1.SelectedItems.Count != 0)foreach (ListViewItem titem in listView1.SelectedItems)titem.Selected = false;if (item != null && item.Tag.Equals("0")){item.Selected = true;。

操作系统文件管理实验报告

操作系统文件管理实验报告

操作系统文件管理实验报告操作系统文件管理实验报告一、实验目的操作系统是计算机系统中的核心软件之一,负责管理计算机硬件资源和提供用户与计算机硬件之间的接口。

文件管理是操作系统的重要功能之一,它涉及到文件的创建、读取、写入、删除等操作。

本次实验旨在通过编写简单的文件管理程序,加深对操作系统文件管理机制的理解。

二、实验环境本次实验使用C语言编写,运行在Linux操作系统上。

实验过程中使用了gcc 编译器和Linux系统提供的文件管理函数。

三、实验内容1. 文件的创建在操作系统中,文件是存储在存储介质上的数据集合。

文件的创建是指在存储介质上分配一块空间,并为其分配一个唯一的文件名。

在本次实验中,我们使用了Linux系统提供的open函数来创建文件。

open函数接受两个参数,第一个参数是文件名,第二个参数是文件的打开模式。

通过调用open函数,我们可以在指定的路径下创建一个文件。

2. 文件的读取和写入文件的读取和写入是文件管理的核心操作。

在本次实验中,我们使用了Linux 系统提供的read和write函数来实现文件的读取和写入。

read函数接受三个参数,第一个参数是文件描述符,第二个参数是存储读取数据的缓冲区,第三个参数是要读取的数据的长度。

write函数也接受三个参数,第一个参数是文件描述符,第二个参数是要写入的数据的缓冲区,第三个参数是要写入的数据的长度。

通过调用read和write函数,我们可以实现对文件的读取和写入操作。

3. 文件的删除文件的删除是指在存储介质上释放文件占用的空间,并删除文件的相关信息。

在本次实验中,我们使用了Linux系统提供的unlink函数来删除文件。

unlink函数接受一个参数,即要删除的文件名。

通过调用unlink函数,我们可以删除指定的文件。

四、实验步骤1. 创建文件首先,我们使用open函数创建一个文件。

在调用open函数时,需要指定文件的路径和文件的打开模式。

文件的路径可以是绝对路径或相对路径,文件的打开模式可以是只读、只写、读写等。

文件管理系统源代码

文件管理系统源代码

文件管理系统一、实验目的通过设计一个多用户文件系统,了解操作系统中文件的组织与管理,熟悉文件管理所用的数据结构,加深对文件系统内部功能实现过程的理解。

二、实验内容1.用C语言或C++语言设计一个最多包括N个用户的多用户文件系统,约定每个用户最多保存M个文件。

同时限制一个用户在进入系统后,最多打开L个文件。

2.系统应具备一定的健壮性。

即能够检查用户所输入命令的正确性,出错时显示出必要的信息。

另外,对文件需设置必要的保护措施。

3.文件目录结构采用两级目录结构:主文件目录和用户文件目录#include"io.h"#include"conio.h"#include"stdio.h"#include"stdlib.h"#include"malloc.h"#include"string.h"#include"ctype.h"#define N 30 /*用户数*/#define M 20 /*一个用户可保存M个文件*/#define L 5 /*用户只能一次打开L个文件*/typedef struct MFD /*主文件目录*/{char username[100];char password[100];FILE fp; /*文件指针*/}MFD;///////////typedef struct UFD /*用户文件目录*/{char filename[256];char protect; /*保护码*/int length; /*文件长度*/}UFD;//////////typedef struct OFD /*打开文件目录*/{char filename[256];char opencode; /*打开保护码*/int fp; /*读写指针*/}OFD;//////////typedef struct COMM /*命令串*/{char string[256]; /*命令*/struct COMM *next;/*后继指针*/}COMM;////////////MFD mainfd[N]; /*主文件目录数组*/UFD userfd[M]; /*用户文件目录数组*/OFD openfd[L]; /*打开文件目录数组*/////////COMM*command; /*命令串指针*/char username[10];int usernum,savenum,opennum;int workfile;void init();void init_ufd(char *username);/*初始化用户文件目录*/ void mesg(char *str); /*消息*/char *getpass(); /*设置口令函数声明*/ char *getuser(); /*设置用户函数声明*/ COMM *readcommand(); /*读命令串函数声明*/ void login(); /*用户登录*/void logout(); /*用户注销*/void setpass(); /*设置口令*/void create(); /*创建文件*/void mydelete(); /*删除文件*/void myread(); /*读文件*/void myopen(); /*打开文件*/void myclose(); /*关闭文件*/void mywrite(); /*写文件*/void help(); /*帮助*/void dir(); /*列文件目录*/void mycopy(); /*复制文件*/void myrename(); /*重命名文件名*//////////////void main(){init();for(;;){readcommand();if(strcmp(command->string,"create")==0)create();else if(strcmp(command->string,"delete")==0)mydelete();else if(strcmp(command->string,"open")==0)myopen();else if(strcmp(command->string,"close")==0)myclose();else if(strcmp(command->string,"read")==0)myread();else if(strcmp(command->string,"write")==0)mywrite();else if(strcmp(command->string,"copy")==0)mycopy();else if(strcmp(command->string,"rename")==0)myrename();else if(strcmp(command->string,"login")==0)login();else if(strcmp(command->string,"setpass")==0)setpass();else if(strcmp(command->string,"logout")==0)logout();else if(strcmp(command->string,"help")==0)help();else if(strcmp(command->string,"dir")==0)dir();else if(strcmp(command->string,"exit")==0)break;elsemesg("Bad command!");}}///////////////////void init(){FILE *fp;char tempname[20],temppass[20];int i=0;usernum=0;savenum=0;opennum=0;strcpy(username,"");if((fp=fopen("mainfile.txt","r"))!=NULL){while(!feof(fp)){strcpy(tempname,"");fgets(tempname,20,fp);if(strcmp(tempname,"")!=0){fgets(temppass,20,fp);tempname[strlen(tempname)-1]='\0';temppass[strlen(tempname)-1]='\0';strcpy(mainfd[usernum].username,tempname);strcpy(mainfd[usernum].password,tempname);usernum++;}}fclose(fp);}}///////////////////////void init_ufd(char *username)/*初始化用户文件目录*/{FILE *fp;char tempfile[100],tempprot;int templength;savenum=0;opennum=0;workfile=-1;if((fp=fopen(username,"w+"))!=NULL){while(!feof(fp)){strcpy(tempfile,"");fgets(tempfile,50,fp);if(strcmp(tempfile,"")!=0){fscanf(fp,"%c",&tempprot);fscanf(fp,"%d",&templength);tempfile[strlen(tempfile)-1]='\0';strcpy(userfd[savenum].filename,tempfile);userfd[savenum].protect=tempprot;userfd[savenum].length=templength;savenum++;fgets(tempfile,50,fp);}}}fclose(fp);}////////////////////void mesg(char *str){printf("\n %s\n",str);}////////////////////////////char *getuser(){char username[20];char temp;int i;username[0]='\0';for(i=0;i<10;){while(!kbhit());temp=getch();if(isalnum(temp)||temp=='_'||temp==13){username[i]=temp;if(username[i]==13){username[i]='\0';break;}putchar(temp);i++;username[i]='\0';}}return(username);}///////////////////char *getpass(){char password[20];char temp;int i;password[0]='\0';for(i=0;i<10;){while(!kbhit());temp=getch();if(isalnum(temp)||temp=='_'||temp==13){password[i]=temp;if(password[i]==13){password[i]='\0';break;}putchar('*');i++;password[i]='\0';}}return(password);}///////////////COMM *readcommand(){char temp[256];char line[256];int i,end;COMM *newp,*p;command=NULL;strcpy(line,"");while(strcmp(line,"")==0){printf("\nc:\\>");gets(line);}for(i=0;i<=strlen(line);i++){if(line[i]==' ')i++;end=0;while(line[i]!='\0'&&line[i]!=' '){temp[end]=line[i];end++;i++;}if(end>0){temp[end]='\0';newp=(COMM *)malloc(sizeof(COMM *));strcpy(newp->string,temp);newp->next=NULL;if(command==NULL)command=newp;else{p=command;while(p->next!=NULL)p=p->next;p->next=newp;}}}p=command;return(command);}/////////////////////////////void login() /*用户注册*/{FILE *fp;int i;char password[20],confirm[20],tempname[20];if(command->next==NULL){printf("\n User Name:");strcpy(tempname,getuser());}else if(command->next->next!=NULL){mesg("Too many parameters!");return;}elsestrcpy(tempname,command->next->string);for(i=0;i<usernum;i++)if(strcmp(mainfd[i].username,tempname)==0)break; /*从mainfd表中查找要注册的用户*/ if(i>=usernum) /*新用户*/{printf("\n new user account,enter your password twice!");printf("\n Password:");strcpy(password,getpass());/*输入口令且返回之*/printf("\n Password:");strcpy(confirm,getpass()); /*第二次输入口令*/if(strcmp(password,confirm)==0)/*用户数不能超过N*/{if(usernum>=N)mesg("Create new account false!number of user asscount limited.\n login fasle!");else{strcpy(mainfd[usernum].username,tempname);/*把新用户和口令填入mainfd中*/strcpy(mainfd[usernum].password,password);usernum++;strcpy(username,tempname);mesg("Create a new user!\n login success!");init_ufd(username); /*初始化用户文件目录*/fp=fopen("mainfile.txt","w+"); /*把新用户填入mainfile.txt文件中*/for(i=0;i<usernum;i++){fputs(mainfd[i].username,fp);fputs("\n",fp);fputs(mainfd[i].password,fp);fputs("\n",fp);}fclose(fp);}}else{mesg("Create new account false! Error password.");mesg("login false!");}}else{printf("\n Password:");strcpy(password,getpass());if(strcmp(mainfd[i].password,password)!=0)mesg("Login false! Error password.");else{mesg("Login success!");strcpy(username,tempname);init_ufd(username);}}}/////////////////////////void logout() /*用户注销*/{if(command->next!=NULL)mesg("Too many parameters!");else if(strcmp(username,"")==0)mesg("No user login!");else{strcpy(username,"");opennum=0;savenum=0;workfile=-1;mesg("User logout!");}}////////////////////void setpass() /*修改口令*/{int i=0;FILE *fp;char oldpass[20],newpass[20],confirm[20];if(strcmp(username,"")==0)mesg("No user login!");else{printf("\n Old password:");strcpy(oldpass,getpass());for(int i=0;i<usernum;i++){if(strcmp(mainfd[i].username,username)==0)break;}if(strcmp(mainfd[i].password,oldpass)!=0)mesg("Old password error!");else{printf("\n New password:");strcpy(newpass,getpass());printf("\n Confirm password:");strcpy(confirm,getpass());if(strcmp(newpass,confirm)!=0)mesg("Password not change! confirm different.");else{strcpy(mainfd[i].password,newpass);mesg(" Password change !");fp=fopen("mainfile.txt","w+");for(i=0;i<usernum;i++){fputs(mainfd[i].username,fp);fputs("\n",fp);fputs(mainfd[i].password,fp);fputs("\n",fp);}fclose(fp);}}}}////////////////void create(){int i=0;FILE *fp;if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next!=NULL)mesg("Too many parameters!");else{for(i=0;i<savenum;i++){if(strcmp(userfd[i].filename,command->next->string)==0)break;}if(i<savenum)mesg("Error! the file already existed!");else if(savenum>=M)mesg("Error! connot create file! number of files limited!");else{strcpy(userfd[savenum].filename,command->next->string);userfd[i].protect='r';userfd[i].length=rand();savenum++;mesg("Create file success!");fp=fopen(username,"w+");for(i=0;i<savenum;i++){fputs(userfd[i].filename,fp);fputs("\n",fp);fprintf(fp,"%c\n%d\n",userfd[i].protect,userfd[i].length);}fclose(fp);}}}/////////////////void mydelete() /*删除*/{int i=0;int tempsave=0;FILE *fp;if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next!=NULL)mesg("Too many parameters!");else{for(i=0;i<savenum;i++){if(strcmp(userfd[i].filename,command->next->string)==0)break;}if(i>=savenum)mesg("Error! the file not existed!");else{tempsave=i;for(i=0;i<opennum;i++){if(strcmp(command->next->string,openfd[i].filename)==0)break;}if(i>=opennum)mesg("File not open");////////////////////////////////////////////else{if(tempsave==savenum-1)savenum--;else{for(;tempsave<savenum-1;tempsave++){strcpy(userfd[tempsave].filename,userfd[tempsave+1].filename);userfd[tempsave].protect=userfd[tempsave+1].protect;userfd[tempsave].length=userfd[tempsave+1].length;}savenum--;}mesg("Delete file success!");fp=fopen(username,"w+");for(i=0;i<savenum;i++){fputs(userfd[i].filename,fp);fputs("\n",fp);fprintf(fp,"%c\n%d\n",userfd[i].protect,userfd[i].length);}fclose(fp);}}}}//////////////////void myread() /*读*/{int i=0;int tempsave=0;char tempfile[100];if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next!=NULL)mesg("Too many parameters!");elsestrcpy(tempfile,command->next->string);for(i=0;i<savenum;i++){if(strcmp(tempfile,userfd[i].filename)==0)break;}if(i>=savenum)mesg("File not existed!");else{tempsave=i;for(i=0;i<opennum;i++){if(strcmp(tempfile,openfd[i].filename)==0)break;}if(i>=opennum)mesg("File not opened");else{if(userfd[tempsave].length<1000)printf("\n The file size is %d KB",userfd[tempsave].length);else if(userfd[tempsave].length==1000)printf("\n The file size is 1000 KB");elseprintf("\n The file size is %d,%d KB",userfd[tempsave].length/1000,userfd[tempsave].length%1000);mesg("File read");}}}}/////////////////void myopen()/*打开*/{int i=0;int type=0;char tempcode;char tempfile[100];if(strcmp(username,"")==0)mesg("No user login!");else if(command->next==NULL)mesg("Too few parameters!");{strcpy(tempfile,"");tempcode='r';if(strcmp(command->next->string,"/r")==0){tempcode='r';type=1;}else if(strcmp(command->next->string,"/w")==0){tempcode='w';type=1;}else if(strcmp(command->next->string,"/d")==0){tempcode='d';type=1;}else if(command->next->string[0]=='/')mesg("Error! /r/w/d request!");else if(command->next->next!=NULL)mesg("Too many parameters!");elsestrcpy(tempfile,command->next->string);if(type==1){if(command->next->next!=NULL){if(command->next->next->next!=NULL)mesg("Too many parameters!");elsestrcpy(tempfile,command->next->next->string);}elsemesg("Too few parameters!");}if(strcmp(tempfile,"")){for(i=0;i<savenum;i++){if(strcmp(tempfile,userfd[i].filename)==0)break;}if(i>=savenum)mesg("File not existed!");else{for(i=0;i<opennum;i++){if(strcmp(tempfile,openfd[i].filename)==0)break;}if(i<opennum){mesg("File already opened!");if(openfd[i].opencode!=tempcode){openfd[i].opencode=tempcode;mesg("File permission changed!");}}else if(opennum>=L){mesg("Error! connot open file! number of opened files limited!");}else{strcpy(openfd[opennum].filename,tempfile);openfd[opennum].opencode=tempcode;workfile=opennum;opennum++;mesg("File open success!");}}}}}///////////////////////void myclose()/*关闭*/{int i=0;int tempsave=0;char tempfile[100];if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next!=NULL)mesg("Too many parameters!");else{strcpy(tempfile,command->next->string);for(i=0;i<savenum;i++){if(strcmp(tempfile,userfd[i].filename)==0)break;}if(i>=savenum)mesg("File not existed!");else{for(i=0;i<opennum;i++){if(strcmp(tempfile,openfd[i].filename)==0)break;}if(i>=opennum)mesg("File not opened");else{if(i==opennum-1)opennum--;else{for(;i<opennum-1;i++){strcpy(openfd[i].filename,openfd[i+1].filename);openfd[i].opencode=openfd[i+1].opencode;}opennum--;}mesg("Close file success!");}}}}/////////////////////////void mywrite()/*写*/{int i=0;int tempsave=0;char tempfile[100];if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next!=NULL)mesg("Too many parameters!");else{strcpy(tempfile,command->next->string);for(i=0;i<savenum;i++){if(strcmp(tempfile,userfd[i].filename)==0)break;}if(i>=savenum)mesg("File not existed!");else{tempsave=i;for(i=0;i<opennum;i++){if(strcmp(tempfile,openfd[i].filename)==0)break;}if(i>=opennum)mesg("File not opened");else{mesg("File write");int tt=rand();if(userfd[tempsave].length<=1000)printf("\n The file size from %d KB to %d KB",userfd[tempsave].length,userfd[tempsave].length+tt);/* else if(userfd[tempsave].lenght=1000)printf("\n The file size from 1000 KB");*/elseprintf("\n The file size form %d,%d KB to %d,%d KB",userfd[tempsave].length/1000,userfd[tempsave].length%1000,userfd[tempsave].length+tt/10 00,userfd[tempsave].length+tt%1000);userfd[tempsave].length=userfd[tempsave].length+tt;}}}}///////////////////void help()/*帮助*/{static char *cmd[]={"login","setpass","logout","create","open","read","write","close","delete","dir","help","exit","copy","rename"};static char *cmdhlp[]={"aommand format: login [<username>]","command format:setpass","command format:logout","command format:create <filename>","command format:open [/r/w/d] <filename>","command format:read <filename>","command format:write <filename>","command format:close <filename>","command format:delete <filename>","command format:dir [/u/o/f]","command format:help [<command>]","command format:exit","command format:copy <source filename> <destination filename>","command format:rename <old filename> <new filename>"};static char *detail[]={"explain:user login in the file system.","explain:modify the user password.","explain:user logout the file system.","explain:creat a new file.","explain:/r -- read only [deflaut]\n\t /w -- list opened files \n\t /d --read,modify and delete.","explain:read the file.","explain:modify the file.","explain:close the file.","explain:delete the file.","explain:/u -- list the user account\n\t /0 -- list opened files\n\t /f --list user file[deflaut].","explain:<command> -- list the command detail format and explain.\n\t [deflaut] list the command.","explain:exit from the file sysytem.","explain:copy from one file to another file.","explain:modify the file name."};int helpnum=14;int i=0;if(command->next==NULL){mesg(cmdhlp[10]);mesg(detail[10]);mesg("step 1: login");printf("\t if old user then login,if user not exist then create new user");mesg("step 2: open the file for read(/r),write(/w)or delete(/d)");printf("\t you can open one or more files.one command can open one file");mesg("step 3: read,write or delete some one file");printf("\t you can operate one of the opened files.one command can open one file");mesg("step 4: close the open file");printf("\t you can close one of the opened files.one command can open one file");mesg("step 5: user logout.close all the user opened files");printf("\n command list:");for(i=0;i<helpnum;i++){if(i%4==0)printf("\n");printf(" %-10s",cmd[i]);}}else if(command->next->next!=NULL)mesg("Too many parameters!");else{for(i=0;i<helpnum;i++){if(strcmp(command->next->string,cmd[i])==0)break;}if(i>=helpnum)mesg("the command not existed!");else{mesg(cmdhlp[i]);mesg(detail[i]);}}}//////////////////////void dir()/*列目录文件*/{int i=0;int type=0;char tempcode;if(strcmp(username,"")==0)mesg("No user login!");else{if(command->next==NULL){tempcode='f';}else{if(strcmp(command->next->string,"/u")==0){tempcode='u';}else if(strcmp(command->next->string,"/o")==0){tempcode='o';}else if(strcmp(command->next->string,"/f")==0){tempcode='f';}else if(command->next->string[0]=='/')mesg("Error! /u/o/f request!");else if(command->next->next!=NULL)mesg("Too many parameters!");}if('u'==tempcode){printf("list the user account\n");printf("usename\n");for(i=0;i<usernum;i++){printf("%s\n",mainfd[i].username);}}else if('f'==tempcode){printf("list opened files\n");printf("filename length protect\n");for(i=0;i<savenum;i++){printf("%s%s%d%s%s%c\n",userfd[i].filename," ",userfd[i].length,"KB"," ",userfd[i].protect);}}else if('o'==tempcode){printf("list user files\n");printf("filename opencode\n");for(i=0;i<opennum;i++){printf("%s%s%c\n",openfd[i].filename," ",openfd[i].opencode);}}}}/////////////////////////void mycopy()/*复制*/{char sourfile[256],destfile[256];int i=0,j=0,temp=0;FILE *fp;char tempchar;if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next==NULL)mesg("Too few parametets!");else if(command->next->next->next!=NULL)mesg("Too many parameters!");else{strcpy(sourfile,command->next->string);strcpy(destfile,command->next->next->string);for(i=0;i<savenum;i++){if(strcmp(sourfile,userfd[i].filename)==0)break;}temp=i;if(i>=savenum)printf("\n the source file not eixsted!");else{for(i=0;i<opennum;i++){if(strcmp(sourfile,openfd[i].filename)==0)break;}if(i>=opennum)printf("\n the source file not opened!");else{for(j=0;j<opennum;j++){if(strcmp(destfile,openfd[i].filename)==0)break;}if(j<opennum)mesg("Error! the destination file opened,you must close it first.");else{for(j=0;j<savenum;j++){if(strcmp(destfile,userfd[i].filename)==0)break;}if(j<savenum){mesg("Warning! the destination file exist!");printf("\n Are you sure to recover if ? [Y/N]");while(!kbhit());tempchar=getch();if(tempchar=='N'||tempchar=='n')mesg("Cancel! file not copy.");else if(tempchar=='Y'||tempchar=='y'){mesg("File copy success!file recovered!");userfd[j].length=userfd[i].length;userfd[j].protect=userfd[i].protect;fp=fopen(username,"w+");for(i=0;i<savenum;i++){fputs(userfd[i].filename,fp);fputs("\n",fp);fprintf(fp,"%C\n%d\n",userfd[i].protect,userfd[i].length);}fclose(fp);}}else if(savenum>=M)mesg("copy false! file total limited.");else{strcpy(userfd[savenum].filename,destfile);userfd[savenum].length=userfd[temp].length;userfd[savenum].protect=userfd[temp].protect;savenum++;fp=fopen(username,"w+");for(i=0;i<savenum;i++){fputs(userfd[i].filename,fp);fputs("\n",fp);fprintf(fp,"%c\n%d\n",userfd[i].protect,userfd[i].length);}fclose(fp);mesg("File copy success!");}}}}}}///////////////////////void myrename()/*文件重命名*/{char oldfile[256],newfile[256];int i=0,temp=0;if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next==NULL)mesg("Too few parametets!");else if(command->next->next->next!=NULL)mesg("Too many parameters!");else{strcpy(oldfile,command->next->string);strcpy(newfile,command->next->next->string);for(i=0;i<savenum;i++){if(strcmp(oldfile,userfd[i].filename)==0)break;}temp=i;if(temp>=savenum)printf("\n the source file not eixsted!");else if(temp!=i&&i<savenum){printf("\n newfile and the existing files is the same name, please re-naming!");}else{for(i=0;i<opennum;i++){if(strcmp(oldfile,openfd[i].filename)==0)break;}if(i>=opennum)printf("\n the source file not opened!");else if(strcmp(oldfile,newfile)==0){printf("Rename false! oldfile and newfile can not be the same.");}else{strcpy(openfd[i].filename,newfile);strcpy(userfd[temp].filename,newfile);mesg("Rename file success!\n");}}}}。

简单的文档管理C语言源代码

简单的文档管理C语言源代码

#include<stdio.h>#include<string.h>#include<stdlib.h>#define N 10struct library{int num;char book_name[30];char writer[30];char sort_num[3];char pub_company[30];char pub_time[30];char prise[30];};typedef struct library LIB; struct history{char his_time[30];char his_name[30];}ANJIAN={"2008","许霆"};LIB lib[N];int all=0;int menu(void);void history(void);void book(void);int bookmenu(void);void write(void);void input(void);void search(void);void xiugai(void);void output(void);main(){for(;;){switch(menu()){case 1:history();break;case 2:book();break;case 3:write();break;case 0:exit(1);break;}}}int menu(void){char m[3];int n; printf(" ************************欢迎进入法院文档管理系统******************************\n\n");printf("\t欢迎使用本院文档管理系统,本系统将为您提供历史案件信息查询,工作学习书籍查阅管理。

操作系统磁盘文件管理源码

操作系统磁盘文件管理源码

页眉#include<stdio.h>#include<string.h>#include<stdlib.h>#define MEM_D_SIZE 1024*1024 //总磁盘空间为1M#define DISKSIZE 1024//磁盘块的大小1K//磁盘块数目1K#define DISK_NUM 1024#define FATSIZE DISK_NUM*sizeof(struct fatitem) //FAT表大小#define ROOT_DISK_NO FATSIZE/DISKSIZE+1 //根目录起始盘块号#define ROOT_DISK_SIZE sizeof(struct direct) //根目录大小//路径最大长度为#define DIR_MAXSIZE 1024 1KB//最大子目录数5 #define MSD 5//最大文件深度为5 #define MOFN 5//最大写入文字长度128KB #define MAX_WRITE 1024*128struct fatitem /* size 8*/{int item; /*存放文件下一个磁盘的指针*/char em_disk; /*磁盘块是否空闲标志位0 空闲*/ };页脚页眉struct direct{/*-----文件控制快信息-----*/struct FCB{char name[9]; /*文件/目录名8位*/char property; /*属性1位目录0位普通文件*/ int size; /*文件/目录字节数、盘块数)*/int firstdisk; /*文件/目录起始盘块号*/int next; /* 子目录起始盘块号*/int sign; /*1是根目录0 不是根目录*/}directitem[MSD+2];};struct opentable{struct openttableitem{char name[9]; /* 文件名*/*/ 起始盘块号int firstdisk; /*页脚页眉int size; /*文件的大小*/}openitem[MOFN];int cur_size; /*当前打文件的数目*/};struct fatitem *fat; /*FAT表*/struct direct *root; /*根目录*/struct direct *cur_dir; /*当前目录*/struct opentable u_opentable; /*文件打开表*/ int fd=-1; /*文件打开表的序号*/char *bufferdir; /*记录当前路径的名称*/ char *fdisk; /*虚拟磁盘起始地址*/void initfile();void format();void enter();void halt();int create(char *name);int open(char *name);int close(char *name);int write(int fd,char *buf,int len);int read(int fd,char *buf);页脚页眉int del(char *name);int mkdir(char *name);int rmdir(char *name);void dir();int cd(char *name);void print();void show();void initfile(){fdisk = (char *)malloc(MEM_D_SIZE*sizeof(char)); /*申请1M空间*/ format();}void format(){int i;FILE *fp;表地址,引导区向后偏计算fat = (struct fatitem *)(fdisk+DISKSIZE); /*FAT 移1k)*/页脚页眉/*-----初始化FAT表------------*/fat[0].item=-1; /*引导块*/fat[0].em_disk='1';for(i=1;i<ROOT_DISK_NO-1;i++) /*存放FAT表的磁盘块号*/{fat[i].item=i+1;fat[i].em_disk='1';}*/ /*存放根目录的磁盘块号fat[ROOT_DISK_NO].item=-1;fat[ROOT_DISK_NO].em_disk='1';for(i=ROOT_DISK_NO+1;i<DISK_NUM;i++){fat[i].item = -1;fat[i].em_disk = '0';}/*-----------------------------------------------*/root = (struct direct *)(fdisk+DISKSIZE+FATSIZE); /*根目录的地址*/ /*初始化目录*//*------------------*/ 指向当前目录的目录项页脚页眉root->directitem[0].sign = 1;root->directitem[0].firstdisk = ROOT_DISK_NO;strcpy(root->directitem[0].name,.);root->directitem[0].next = root->directitem[0].firstdisk;root->directitem[0].property = '1';root->directitem[0].size = ROOT_DISK_SIZE;/*------- 指向上一级目录的目录项---------*/root->directitem[1].sign = 1;root->directitem[1].firstdisk = ROOT_DISK_NO;strcpy(root->directitem[1].name,..);root->directitem[1].next = root->directitem[0].firstdisk; root->directitem[1].property = '1';root->directitem[1].size = ROOT_DISK_SIZE;if((fp = fopen(disk.dat,wb))==NULL){printf(Error:\n Cannot open file \n);return;}for(i=2;i<MSD+2;i++) /*--*/ 子目录初始化为空{ root->directitem[i].sign = 0;root->directitem[i].firstdisk = -1;页脚页眉strcpy(root->directitem[i].name,\);root->directitem[i].next = -1;root->directitem[i].property = '0';root->directitem[i].size = 0;}if((fp = fopen(disk.dat,wb))==NULL)printf(Error:\n Cannot open file \n);return;}把虚拟磁盘空间保存到磁盘文件中if(fwrite(fdisk,MEM_D_SIZE,1,fp)!=1) /**/ {printf(Error:\n File write error! \n);}fclose(fp);}void enter()页脚页眉{FILE *fp;int i;fdisk = (char *)malloc(MEM_D_SIZE*sizeof(char)); /*申请1M空间*/if((fp=fopen(disk.dat,b))==NULL)printf(Error:\nCannot open file\n);return;}读入虚拟磁盘disk.dat /* if(!fread(fdisk,MEM_D_SIZE,1,fp)) 把磁盘文件空间(内存)*/{printf(Error:\nCannot read file\n);exit(0);}fat = (struct fatitem *)(fdisk+DISKSIZE); /* 找到FAT表地址*/找到根目录地址root = (struct direct *)(fdisk+DISKSIZE+FATSIZE);/**/ fclose(fp);初始化用户打开表/*--------------------------------*/for(i=0;i<MOFN;i++){页脚页眉strcpy(u_opentable.openitem[i].name,\);u_opentable.openitem[i].firstdisk = -1;u_opentable.openitem[i].size = 0;}u_opentable.cur_size = 0;cur_dir = root; /*当前目录为根目录*/bufferdir = (char *)malloc(DIR_MAXSIZE*sizeof(char));strcpy(bufferdir,Root:);}void halt(){FILE *fp;int i;if((fp=fopen(disk.dat,wb))==NULL){printf(Error:\nCannot open file\n);return;}内容读入磁盘/*if(!fwrite(fdisk,MEM_D_SIZE,1,fp)) 内存(把虚拟磁盘空间)页脚页眉文件disk.dat */{printf(Error:\nFile write error!\n);}fclose(fp);free(fdisk);free(bufferdir);return;}int create(char *name){int i,j;if(strlen(name)>8) /*文件名大于8位*/return(-1);for(j=2;j<MSD+2;j++) /*检查创建文件是否与已存在的文件重名*/ {if(!strcmp(cur_dir->directitem[j].name,name))页脚页眉break;}if(j<MSD+2) /*文件已经存在*/return(-4);for(i=2;i<MSD+2;i++) /*找到第一个空闲子目录*/{if(cur_dir->directitem[i].firstdisk==-1)break;}if(i>=MSD+2) /*无空目录项*/return(-2);if(u_opentable.cur_size>=MOFN) /*打开文件太多*/return(-3);for(j=ROOT_DISK_NO+1;j<DISK_NUM;j++) /*找到空闲盘块j 后退出*/ {if(fat[j].em_disk=='0')break;}if(j>=DISK_NUM)页脚页眉return(-5);fat[j].em_disk = '1'; /*将空闲块置为已经分配*/ /*-----------填写目录项-----------------*/strcpy(cur_dir->directitem[i].name,name);cur_dir->directitem[i].firstdisk = j;cur_dir->directitem[i].size = 0;cur_dir->directitem[i].next = j;cur_dir->directitem[i].property = '0';/*---------------------------------*/fd = open(name);return 0;}int open(char *name){int i, j;for(i=2;i<MSD+2;i++) /*文件是否存在*/{if(!strcmp(cur_dir->directitem[i].name,name)) break;页脚页眉}if(i>=MSD+2)return(-1);/*--------是文件还是目录-----------------------*/if(cur_dir->directitem[i].property=='1')return(-4);/*--------文件是否打开-----------------------*/for(j=0;j<MOFN;j++){if(!strcmp(u_opentable.openitem[j].name,name)) break;}if(j<MOFN) /*文件已经打开*/return(-2);if(u_opentable.cur_size>=MOFN) /*文件打开太多*/return(-3);/*--------查找一个空闲用户打开表项-----------------------*/for(j=0;j<MOFN;j++)页脚页眉{if(u_opentable.openitem[j].firstdisk==-1)break;}/*--------------填写表项的相关信息------------------------*/u_opentable.openitem[j].firstdisk = cur_dir->directitem[i].firstdisk;strcpy(u_opentable.openitem[j].name,name);u_opentable.openitem[j].size = cur_dir->directitem[i].size;u_opentable.cur_size++;/*----------返回用户打开表表项的序号--------------------------*/return(j);}int close(char *name){int i;for(i=0;i<MOFN;i++){if(!strcmp(u_opentable.openitem[i].name,name)) break;}页脚页眉if(i>=MOFN)return(-1);/*-----------清空该文件的用户打开表项的内容---------------------*/ strcpy(u_opentable.openitem[i].name,\);u_opentable.openitem[i].firstdisk = -1;u_opentable.openitem[i].size = 0;u_opentable.cur_size--;return 0;}int write(int fd, char *buf, int len){char *first;int item, i, j, k;int ilen1, ilen2, modlen, temp;/*----------用$ 字符作为空格# 字符作为换行符-----------------------*/ char Space = 32;char Endter= '\n';for(i=0;i<len;i++)页脚页眉{if(buf[i] == '$')buf[i] = Space;else if(buf[i] == '#')buf[i] = Endter;}-----------------------*/ /*----------读取用户打开表对应表项第一个盘块号item = u_opentable.openitem[fd].firstdisk;-------------------------*/ /*-------------找到当前目录所对应表项的序号for(i=2;i<MSD+2;i++){if(cur_dir->directitem[i].firstdisk==item)break;}存放当前目录项的下标-*/ temp = i; /*- /*------找到的是该文件的最后一块磁盘块-------------------*/ itemwhile(fat[item].item!=-1){查找该文件的下一盘块item =fat[item].item; /*---*/页脚页眉}/*-----计算出该文件的最末地址-------*/first = fdisk+item*DISKSIZE+u_opentable.openitem[fd].size%DISKSIZE;/*-----如果最后磁盘块剩余的大小大于要写入的文件的大小-------*/if(DISKSIZE-u_opentable.openitem[fd].size%DISKSIZE>len){strcpy(first,buf);u_opentable.openitem[fd].sizeu_opentable.openitem[fd].size+len;cur_dir->directitem[temp].size=cur_dir->directitem[temp].size+len;}else{for(i=0;i<(DISKSIZE-u_opentable.openitem[fd].size%DISKSIZE);i++) {/* 写一部分内容到最后一块磁盘块的剩余空间(字节)*/first[i] = buf [i];}还剩下多少字节未存字节) (/*----- 计算分配完最后一块磁盘的剩余空间储-------*/页脚页眉ilen1 = len-(DISKSIZE-u_opentable.openitem[fd].size%DISKSIZE); ilen2 = ilen1/DISKSIZE;modlen = ilen1%DISKSIZE;if(modlen>0)ilen2 = ilen2+1; /*-- 还需要多少块磁盘块-*/for(j=0;j<ilen2;j++){*/ for(i=ROOT_DISK_NO+1;i<DISK_NUM;i++)/*寻找空闲磁盘块{if(fat[i].em_disk=='0')break;}if(i>=DISK_NUM) /*-- -*/ 如果磁盘块已经分配完了return(-1);first = fdisk+i*DISKSIZE; /*--找到的那块空闲磁盘块的起始地址-*/if(j==ilen2-1) /*-- 如果是最后要分配的一块-*/{for(k=0;k<len-(DISKSIZE-u_opentable.openitem[fd].size%DISKSIZE)-j*DI SKSIZE;k++)first[k] = buf[k];页脚页眉}else/*-如果不是要最后分配的一块--*/{for(k=0;k<DISKSIZE;k++)first[k] =buf[k];}找到一块后将它的序号存放在上一块的指i; /*--fat[item].item = 针中-*/fat[i].em_disk = '1'; /*--置找到的磁盘快的空闲标志位为已分配-*/ fat[i].item = -1; /*--它的指针为-1 (即没有下一块)-*/}修改长度/*-- -*/=u_opentable.openitem[fd].sizeu_opentable.openitem[fd].size+len;cur_dir->directitem[temp].size=cur_dir->directitem[temp].size+len;}return 0;}int read(int fd, char *buf)页脚页眉{int len = u_opentable.openitem[fd].size;char *first;int i, j, item;int ilen1, modlen;item = u_opentable.openitem[fd].firstdisk;ilen1 = len/DISKSIZE;modlen = len%DISKSIZE;if(modlen!=0)ilen1 = ilen1+1; /*--计算文件所占磁盘的块数-*/-*/ first = fdisk+item*DISKSIZE; /*--计算文件的起始位置for(i=0;i<ilen1;i++){if(i==ilen1-1) /*-- 如果在最后一个磁盘块-*/{for(j=0;j<len-i*DISKSIZE;j++)buf[i*DISKSIZE+j] = first[j];页脚页眉}else /*--不在最后一块磁盘块-*/{for(j=0;j<len-i*DISKSIZE;j++)buf[i*DISKSIZE+j] = first[j];item = fat[item].item; /*- 查找下一盘块-*/first = fdisk+item*DISKSIZE;}}return 0;}int del(char *name){int i,cur_item,item,temp;for(i=2;i<MSD+2;i++) /*-- 查找要删除文件是否在当前目录中-*/ {if(!strcmp(cur_dir->directitem[i].name,name))break;}cur_item = i; /*--用来保存目录项的序号-*/ ,供释放目录中页脚页眉if(i>=MSD+2) /*--如果不在当前目录中-*/return(-1);是目(不)if(cur_dir->directitem[cur_item].property!='0') /*--如果删除的录-*/return(-3);-*/ 则不能删除,退出for(i=0;i<MOFN;i++) /*--如果文件打开, {if(!strcmp(u_opentable.openitem[i].name,name))return(-2);}该文件的起始盘块号-*/ item = cur_dir->directitem[cur_item].firstdisk;/*-- FATwhile(item!=-1) /*--释放空间, 将表对应项进行修改-*/{temp = fat[item].item;fat[item].item = -1;fat[item].em_disk = '0';item = temp;}释放目录项/*----------------------------------------*/页脚页眉cur_dir->directitem[cur_item].sign = 0;cur_dir->directitem[cur_item].firstdisk = -1;strcpy(u_opentable.openitem[cur_item].name,\);cur_dir->directitem[cur_item].next = -1;cur_dir->directitem[cur_item].property = '0'; cur_dir->directitem[cur_item].size = 0;return 0;}int mkdir(char *name){int i,j;struct direct *cur_mkdir;if(!strcmp(name,.))return(-4);if(!strcmp(name,..))return(-4);if(strlen(name)>8) /*-如果目录名长度大于8位-*/ return(-1);页脚页眉for(i=2;i<MSD+2;i++) /*-如果有空闲目录项退出-*/ {if(cur_dir->directitem[i].firstdisk==-1)break;}-*/ 已满if(i>=MSD+2) /*-目录/文件return(-2);for(j=2;j<MSD+2;j++) /*-判断是否有重名-*/{if(!strcmp(cur_dir->directitem[j].name,name)) break;}if(j<MSD+2) /*-如果有重名-*/return(-3);for(j=ROOT_DISK_NO+1;j<DISK_NUM;j++) /*- 找到空闲磁盘块j 后退出-*/ {if(fat[j].em_disk=='0')break;}if(j>=DISK_NUM)return(-5);页脚页眉fat[j].em_disk='1'; /*-将该空闲块设置为已分配-*//*-------------填写目录项----------*/strcpy(cur_dir->directitem[i].name,name);cur_dir->directitem[i].firstdisk=j;cur_dir->directitem[i].size=ROOT_DISK_SIZE;cur_dir->directitem[i].next=j;cur_dir->directitem[i].property='1';/*-所创目录在虚拟磁盘上的地址( 内存物理地址)-*/cur_mkdir=(structdirect*)(fdisk+cur_dir->directitem[i].firstdisk*DISKSIZE);/*-初始化目录-*//*-指向当前目录的目录项-*/cur_mkdir->directitem[0].sign=0;cur_mkdir->directitem[0].firstdisk=cur_dir->directitem[i].firstdisk; strcpy(cur_mkdir->directitem[0].name,.);cur_mkdir->directitem[0].next=cur_mkdir->directitem[0].firstdisk; cur_mkdir->directitem[0].property='1';cur_mkdir->directitem[0].size=ROOT_DISK_SIZE;页脚页眉/*-指向上一级目录的目录项-*/cur_mkdir->directitem[1].sign=cur_dir->directitem[0].sign;cur_mkdir->directitem[1].firstdisk=cur_dir->directitem[0].firstdisk; strcpy(cur_mkdir->directitem[1].name,..);cur_mkdir->directitem[1].next=cur_mkdir->directitem[1].firstdisk; cur_mkdir->directitem[1].property='1';cur_mkdir->directitem[1].size=ROOT_DISK_SIZE;for(i=2;i<MSD+2;i++) /*-子目录都初始化为空-*/cur_mkdir->directitem[i].sign=0;cur_mkdir->directitem[i].firstdisk=-1;strcpy(cur_mkdir->directitem[i].name,\);cur_mkdir->directitem[i].next=-1;cur_mkdir->directitem[i].property='0';cur_mkdir->directitem[i].size=0;}return 0;}int rmdir(char *name){页脚页眉int i,j,item;struct direct *temp_dir;/*-检查当前目录项中有无该目录-*/for(i=2;i<MSD+2;i++){if(!strcmp(cur_dir->directitem[i].name,name)) break;if(i>=MSD+2) /*-没有这个文件或目录-*/return(-1);if(cur_dir->directitem[i].property!='1')/*-删除的不是目录-*/return(-3);-*/ /*-判断要删除的目录有无子目录temp_dir=(struct direct *)(fdisk+cur_dir->directitem[i].next*DISKSIZE); for(j=2;j<MSD+2;j++){if(temp_dir->directitem[j].next!=-1)break;}有子目录或文件/*-if(j<MSD+2) -*/页脚页眉return(-2);/*------------找到起始盘块号,并将其释放----------------*/item=cur_dir->directitem[i].firstdisk;fat[item].em_disk='0';/*-修改目录项-*/cur_dir->directitem[i].sign=0;cur_dir->directitem[i].firstdisk=-1;strcpy(cur_dir->directitem[i].name,\);cur_dir->directitem[i].next=-1;cur_dir->directitem[i].property='0';cur_dir->directitem[i].size=0;return 0;}void dir(){int i;for(i=2;i<MSD+2;i++){if(cur_dir->directitem[i].firstdisk!=-1) /*-如果存在子目录-*/ {页脚页眉printf(%s\t,cur_dir->directitem[i].name);if(cur_dir->directitem[i].property=='0') /*-文件-*/printf(%d\t\t\n,cur_dir->directitem[i].size); elseprintf(\ <目录>\t\n);}}}int cd(char *name){int i,j,item;char *str;char *temp,*point,*point1;struct direct *temp_dir;temp_dir=cur_dir;str=name;if(!strcmp(\\\,name)){cur_dir = root;strcpy(bufferdir,Root:);页脚页眉return 0;}temp = (char *)malloc(DIR_MAXSIZE*sizeof(char));/*- 最长路径名字分配空间-*/for(i=0;i<(int)strlen(str);i++)temp[i]=str[i];temp[i]='\0';for(j=0;j<MSD+2;j++) /*-查找该子目录是否在当前目录中-*/{if(!strcmp(temp_dir->directitem[j].name,temp))break;}*/ free(temp);/*释放申请的临时空间//if(temp_dir->directitem[j].property!='1') /*-打开的不是目录-*///return(-2);-*/ 不在当前目录if(j>=MSD+2) /*- return(-1);页脚页眉item=temp_dir->directitem[j].firstdisk;/*-当前目录在磁盘中位置-*/temp_dir=(struct direct *)(fdisk+item*DISKSIZE);if(!strcmp(..,name)){if(cur_dir->directitem[j-1].sign!=1) /*-如果上级目录不是根目录-*/{point=strchr(bufferdir,'\\'); // 查找字符串bufferdir中首次出现字符\ 的位置while(point!=NULL){point1=point+1; /*- 减去'\' 所占的空间, 记录下次查找的起始地址-*/ point=strchr(point1,'\\');}将上一级目录删除*(point1-1)='\0'; /*- -*/}}页脚页眉else{//if(name[0] !='\\')bufferdir = strcat(bufferdir,\\\); /*-修改当前目录-*/bufferdir = strcat(bufferdir,name);}-*/ /*-cur_dir=temp_dir; 将当前目录确定下来return 0;}void show(){printf(%s>,bufferdir);}void print(){printf(*********************************************************\n);文件系统设计printf(*********************************************\n); *\n); 命令格式printf(*\t 说明printf(*\tcd 目录名*\n); 更改当前目录页脚页眉printf(*\tmkdir 目录名创建子目录*\n);删除子目录printf(*\trmdir 目录名*\n);显示当前目录的子目录*\n); printf(*\tdir创建文件*\n); printf(*\tcreate 文件名printf(*\tdel 文件名删除文件*\n);*\n); 打开文件printf(*\topen 文件名关闭文件*\n); 文件名printf(*\tcloseprintf(*\tread 读文件*\n);*\n); printf(*\twrite 写文件*\n); printf(*\texit 退出系统printf(*********************************************************\n); }void main(){FILE *fp;char ch;char a[100];char code[11][10];char name[10];int i,flag,r_size;页脚页眉char *contect;contect = (char *)malloc(MAX_WRITE*sizeof(char));if((fp=fopen(disk.dat,b))==NULL){printf(You have not format,Do you want format?(y/n)); scanf(%c,&ch);if(ch=='y'){initfile();printf(Successfully format! \n);}else{return;}}enter();print();页脚页眉show();strcpy(code[0],exit); strcpy(code[1],create); strcpy(code[2],open); strcpy(code[3],close); strcpy(code[4],write); strcpy(code[5], ead);strcpy(code[6],del); strcpy(code[7],mkdir); strcpy(code[8], mdir);strcpy(code[9],dir); strcpy(code[10],cd);while(1){scanf(%s,a);for(i=0;i<11;i++){if(!strcmp(code[i],a)) break;}页脚页眉switch(i){case 0: // 退出文件系统free(contect);halt();return;case 1: // 创建文件scanf(%s,name);flag = create(name);if(flag==-1){printf(Error: \n The length is too long !\n);}else if(flag==-2){printf(Error: \n The direct item is already full !\n);}else if(flag==-3){printf(Error: \n The number of openfile is too much !\n); }页脚页眉else if(flag==-4){printf(Error: \n The name is already in the direct !\n);}else if(flag==-5){printf(Error: \n The disk space is full!\n);}else{printf(Successfully create a file! \n);}show();break;case 2://打开文件scanf(%s,name);fd = open(name);if(fd == -1){printf(Error: \n The open file not exit! \n);页脚页眉}else if(fd == -2){printf(Error: \n The file have already opened! \n); }else if(fd == -3){printf(Error: \n The number of open file is too much! \n); }else if(fd == -4){printf(Error: \n It is a direct,can not open for read or write! \n);}else{printf(Successfully opened! \n);}show();break;case 3://关闭文件页脚页眉scanf(%s,name);flag = close(name);if(flag == -1){printf(Error:\n The file is not opened ! \n); }else{printf(Successfully closed! \n);}show();break;case 4://写文件if(fd ==-1){printf(Error:\n The file is not opened ! \n);}else{printf(Please input the file contect:);scanf(%s,contect);页脚页眉flag=write(fd,contect,strlen(contect));if(flag == 0){printf(Successfully write! \n);}else{printf(Error:\n The disk size is not enough! \n);}}show();break;case 5:// 读文件if(fd ==-1){printf(Error:\n The file is not opened ! \n);}else{flag = read(fd,contect);if(flag == 0)页脚页眉{for(i=0;i<u_opentable.openitem[fd].size;i++){printf(%c,contect[i]);}printf(\ \n);}}show();break;case 6:// 删除文件scanf(%s,name);flag = del(name);if(flag == -1){printf(Error:\n The file not exit! \n);}else if(flag == -2){printf(Error:\n The file is opened,please first close it ! \n);页脚页眉else if(flag == -3){printf(Error:\n The delete is not file ! \n);}else{printf(Successfully delete! \n);}show();break;case 7://创建子目录scanf(%s,name);flag = mkdir(name);if(flag == -1){printf(Error:\n The length of name is to long! \n); }else if(flag == -2)printf(Error:\n The direct item is already full ! \n);}页脚页眉else if(flag == -3){printf(Error:\n The name is already in the direct ! \n);}else if(flag == -4){the the name of or '.' can not as \n printf(Error: '..' direct!\n);}else if(flag == -5){printf(Error: \n The disk space is full!\n);}else if(flag == 0){printf(Successfully make dircet! \n);}show();break;case 8://删除子目录scanf(%s,name);页脚页眉flag = rmdir(name);if(flag == -1){printf(Error:\n The direct is not exist! \n);}else if(flag == -2){printf(Error:\nThe direct has son direct ,please first remove the son dircct!\n);}else if(flag == -3){printf(Error:\n The remove is not direct ! \n);}else if(flag == 0){printf(Successfully remove dircet! \n); }show();break;显示当前子目录case 9://页脚页眉dir();show();break;case 10://更改当前目录scanf(%s,name);flag = cd(name);if(flag == -1){printf(Error:\n The path no correct!\n);}else if(flag == -2){printf(Error:\nThe opened is not direct!\n);}show();break;default:printf(\Error!\n The command is wrong! \n);show();页脚页眉}}}页脚。

操作系统实验参考代码

操作系统实验参考代码

目录实验一WINDOWS进程初识 (2)实验二进程管理 (6)实验三进程同步的经典算法 (10)实验四存储管理 (14)试验五文件系统试验 (18)实验有关(参考)代码实验一WINDOWS进程初识1、实验目的(1)学会使用VC编写基本的Win32 Consol Application(控制台应用程序)。

(2)掌握WINDOWS API的使用方法。

(3)编写测试程序,理解用户态运行和核心态运行。

2、程序清单清单1-1 一个简单的Windows控制台应用程序// hello项目# include <iostream>void main(){std::cout << “Hello, Win32 Consol Application” << std :: endl ;}清单1-2 核心态运行和用户态运行时间比计算// proclist项目# include <windows.h># include <tlhelp32.h># include <iostream.h>// 当在用户模式机内核模式下都提供所耗时间时,在内核模式下进行所耗时间的64位计算的帮助方法DWORD GetKernelModePercentage(const FILETIME& ftKernel,const FILETIME& ftUser){// 将FILETIME结构转化为64位整数ULONGLONG qwKernel=(((ULONGLONG)ftKernel.dwHighDateTime)<<32)+ftKernel.dwLowDateTime;ULONGLONG qwUser=(((ULONGLONG)ftUser.dwHighDateTime)<<32)+ftUser.dwLowDateTime;// 将消耗时间相加,然后计算消耗在内核模式下的时间百分比ULONGLONG qwTotal=qwKernel+qwUser;DWORD dwPct=(DWORD)(((ULONGLONG)100*qwKernel)/qwTotal);return(dwPct);}// 以下是将当前运行过程名和消耗在内核模式下的时间百分数都显示出来的应用程序void main(int argc,char *argv[]){if(argc<2){cout<<"请给出你要查询的程序名"<<endl;exit(0);}// 对当前系统中运行的过程拍取“快照”HANDLE hSnapshot=::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,// 提取当前过程0);// 如果是当前过程,就将其忽略// 初始化过程入口PROCESSENTRY32 pe;::ZeroMemory(&pe,sizeof(pe));pe.dwSize=sizeof(pe);BOOL bMore=::Process32First(hSnapshot,&pe);BOOL found = FALSE;while(bMore){// 打开用于读取的过程if(!strcmp(pe.szExeFile,argv[1])){found = TRUE;HANDLE hProcess=::OpenProcess(PROCESS_QUERY_INFORMA TION,// 指明要得到信息FALSE,// 不必继承这一句柄pe.th32ProcessID);// 要打开的进程if (hProcess!=NULL){// 找出进程的时间FILETIME ftCreation,ftKernelMode,ftUserMode,ftExit;::GetProcessTimes(hProcess,// 所感兴趣的进程&ftCreation,// 进程的启动时间&ftExit,// 结束时间(如果有的话)&ftKernelMode,// 在内核模式下消耗的时间&ftUserMode);// 在用户模式下消耗的时间// 计算内核模式消耗的时间百分比DWORD dwPctKernel=::GetKernelModePercentage(ftKernelMode,// 在内核模式上消耗的时间ftUserMode);// 在用户模式下消耗的时间// 向用户显示进程的某些信息cout<< "process ID: " << pe.th32ProcessID<< ",EXE file:" << pe.szExeFile<< ",%d in Kernel mode: " << dwPctKernel << endl;// 消除句柄::CloseHandle(hProcess);}}// 转向下一个进程bMore=::Process32Next(hSnapshot,&pe);}if(found==FALSE){cout<<"当前系统没有这个可执行程序正在运行"<<endl;exit(0);}}清单1-3 核心态运行和用户态运行时间测试程序#include <stdio.h>main(){int i,j;while(1){for(i=0;i<1000;i++);for(j=1;j<1000;j++) printf(“enter kernel mode running.”);}}实验二进程管理1、实验目的1) 通过创建进程、观察正在运行的进程和终止进程的程序设计和调试操作,进一步熟悉操作系统的进程概念,理解Windows进程的“一生”。

实验设备管理系统-c语言实现

实验设备管理系统-c语言实现

一、设计目的1.1 设计题目:设计实现一个实验设备管理系统。

实验设备信息包括:设备编号,设备种类(如:微机、打印机、扫描仪等等),设备名称,设备价格,设备购入日期,是否报废,报废日期等。

1.2 设计要求(1)能够完成对设备的录入和修改(2)对设备进行分类统计(3)设备的破损耗费和遗损处理(4)设备的查询(5)采用二进制文件方式存储数据,系统以菜单方式工作1.3 系统功能需求分析系统功能需求:设备信息的录入、修改;设备分类统计;设备破损耗费和遗损处理;设备信息查询;二进制文件方式存储数据;菜单方式工作;用户操作流程:运行程序后会弹出菜单界面,根据菜单界面的提示选择需要完成的相应功能即可完成操作。

数据处理流程:通过input函数将用户输入的各信息以二进制文件方式存储数据,后续可根据需要调用change函数、sort函数、search函数以及del函数进行数据的相应处理,最后通过output函数实现数据的输出显示。

二、总体设计实验设备管理系统功能结构图如下所示:三、详细设计3.1 结构体struct equipment_infor//定义结构体包含各设备信息{char ID[20]; //设备编号int sort; //设备种类(1代表微机 2代表打印机 3代表扫描机)char name[20]; //设备名称float price; //设备价格char buy_date[20]; //设备购买日期int state; //设备状态(报废为1,未报废为0)char scrap_date[20]; //设备报废日期}device[NUM];定义结构体数组,其中包含设备所有信息,方便数据信息的录入、输出等。

3.2 主要函数3.2.1 void load()加载已有数据函数void load() //加载已有数据{count=0;FILE* fp_5=fopen("binary.txt","rb");if(fp_5==NULL){return;}for(int i=0;;i++,count++){if(feof(fp_5)!=0){count--;break;}fread(&device[i], sizeof(struct equipment_infor),1,fp_5);}fclose(fp_5);}此函数实现了加载已有信息的功能,能够使得下次运行时上次的数据得以保留,同时计算出了count的值,可提供后续函数for循环的循环条件,一举两得。

c语言编写实验物品管理

c语言编写实验物品管理

c语言编写实验物品管理实验物品管理是指对实验室中的各种仪器设备、试剂药品等实验物品进行管理、使用和维护的一项重要工作。

合理、高效地管理实验物品,能够提高实验室的工作效率,保障实验的质量和安全。

下面将从实验物品管理的重要性、管理方法和实施步骤等方面进行详细介绍。

一、实验物品管理的重要性1.提高工作效率:实验物品的管理是为了更好地利用其资源,提高工作效率。

合理的仓库管理和物品存放,能够使实验人员在进行实验时能够迅速找到所需物品,节省查找时间。

2.保证实验的质量和安全:实验物品的管理可以避免物品的过期、损坏等问题,确保实验所使用的物品的有效性和稳定性。

同时,正确的存储和使用方法可以避免物品的误用和事故的发生,保证实验的安全性。

3.节约成本:实验室是一个资源密集型的地方,各种仪器设备和试剂药品的采购和维护都需要投入一定的成本。

通过合理的物品管理措施,可以减少物品损耗和浪费,节约采购和维护的成本。

4.充分发挥物品的作用:合理的物品管理可以充分发挥实验物品的作用,避免因为存储和使用不当导致物品质量下降或无法正常使用的情况。

二、实验物品管理方法1.物品分类:根据实验物品的性质、用途和特点进行分类。

常见的分类包括试剂药品、仪器设备、耗材、实验工具等。

2.购买计划:制定物品采购计划,根据实验需求、消耗情况和经费预算等因素,明确需要购买的物品种类和数量。

3.仓库管理:建立物品仓库或存放区域,对物品进行统一存放和编号。

物品的入库、出库和库存等操作要有相应的记录和登记。

4.物品使用:根据实验的需要,人员进行物品的领用和归还。

严禁私自擅用实验物品,对实验物品的使用要做到需要使用时才使用。

5.物品维护:定期对仪器设备进行检查和维护,确保其正常运行和使用寿命。

对试剂药品和其他易损耗物品进行注意保管,避免损坏和过期。

6.废弃物处理:对于过期、损坏或不再使用的实验物品要进行正确的处理,避免对环境和人员造成危害。

三、实施实验物品管理的步骤1.制定管理制度:明确实验物品管理的目标、要求和责任。

文件系统模拟实验(C-实验教材)

文件系统模拟实验(C-实验教材)

文件系统实验1.1实验目的和要求1.1.1实验目的通常把文件与管理信息资源的管理程序的集合称为文件系统,它是操作系统中负责存取和管理信息资源的模块,采用统一的方法管理用户信息和系统信息的存储、检索、更新、共享和保护,并为用户提供一套行之有效的文件使用及操作方法。

本实验利用高级语言编写程序模拟文件系统,了解文件系统的基本结构和文件的各种操作方法,加深理解文件系统的内部功能及内部实现,从而帮助学生对各种文件操作命令的实质内容和执行过程有比较深入的了解。

1.1.2实验要求1.采用高级语言编写程序模拟文件系统,文件系统采用多级目录结构,实现对文件和目录的创建、删除、重命名、变更权限、显示文件内容、修改文件内容等操作。

2.撰写实验报告,报告应包含以下内容:(1)实验目的;(2)实验内容;(3)设计思路;(4)程序流程图;(5)程序中主要数据结构和函数说明;(6)带注释的源程序代码;(7)程序运行结果及分析(8)实验收获与体会1.2预备知识1.2.1文件和文件系统1.文件概念现代计算机系统中都配置了外存,大量的程序和数据以文件的形式存放在外存。

如果由用户直接管理文件,不仅要求用户熟悉外存特性,了解各种文件的属性,以及它们在外存上的位置,而且多用户环境下还必须能保持数据的安全性和一致性,这是用户不能胜任的。

因而,现代操作系统中都配备文件系统,以适应系统资源管理和用户使用信息的需要。

文件是指由创建者所定义的、具有文件名的一组相关元素的集合。

用户通过文件名就可对文件进行访问,文件名是由字母或数字组成的字母或数字串,其格式和长度都因系统而异。

操作系统提供文件系统的优点有:(1)便于用户使用。

(2)文件安全可靠。

(3)系统能有效利用存储空间,优化安排不同属主文件的位置。

(4)文件系统还能提供文件共享功能。

2.文件命名在不同的操作系统中对文件名的规定有所不同,文件名的格式和长度因系统而异。

一般来说,文件名由文件名和扩展名两部分组成,前者用于标识文件,后者用于区分文件类型,中间用“.”分割开来,它们都是字母或数字所组成的字母数字串。

操作系统+文件管理+部分代码

操作系统+文件管理+部分代码
}
}
注销用户
void Logout(int a)
{ //注销用户,清除所有文件的登记栏
string str;
char temp[5]="";
for(int i=0;i<L;i++)
{ int i=0;
while(strcmp(MFD[i].Username,"")!=0&&(i<N))//查看MFD,检测用户数是否已满
{ i++; }
if(i>=N){ //如果用户数已满
cout<<"用户数已满. 你必须删除一个用户才继续新建用户"<<endl;
2.3 数据结构设计
系统管理员
typedef struct user //系统管理员
{ char name[5] ; // 登录用户名
char password[10] ; // 登录密码
}user;
用户文件目录
struct UFD
cin>>fil;4) goto Re;//如果文件名长度不符合要求,则要求重新输入
loop:
cout<<"文件属性(r,rw) :";//输入文件属性,读或是读写
open 打开文件
close 关闭文件
read 读文件
write 写文件
(2)列目录时要列出文件名、物理地址、保护码和文件长度;
(3)源文件可以进行读写保护。
提示:
(1)首先应确定文件系统的数据结构:主目录、子目录及活动文件等。主目录和子目录都以文件的形式存放于磁盘,这样便于查找和修改。

C语言编写的文件系统

C语言编写的文件系统

C语言编写的文件系统在计算机科学领域,文件系统是一种用于组织、存储和访问计算机上的文件和目录的方法。

文件系统可以通过使用文件和目录的层次结构来帮助用户更好地管理和组织文件。

在本文中,我们将探讨使用C语言编写文件系统的过程和技术。

一、概述C语言是一种通用的高级编程语言,被广泛应用于系统编程和底层开发。

使用C语言编写文件系统可以使我们更好地理解文件系统的内部工作原理,并具备良好的性能和灵活性。

下面我们将介绍C语言中一些常用的文件系统相关的数据结构和函数。

二、文件系统数据结构1. 文件控制块(FCB):文件控制块是文件系统中的关键数据结构,用于描述文件的属性和相关信息,如文件名、大小、权限等。

我们可以使用结构体来定义文件控制块,并利用指针进行链接和管理。

示例:```ctypedef struct {char filename[MAX_FILENAME_LENGTH];int size;int permission;// 其他属性和信息} FileControlBlock;```2. 目录项:目录项用于存储文件和目录的相关信息以及它们在文件系统中的位置。

每个目录项通常包含文件名、文件类型、起始盘块号等。

示例:```ctypedef struct {char filename[MAX_FILENAME_LENGTH];FileType type;int start_block;// 其他信息} DirectoryEntry;```3. 磁盘块:磁盘块是文件系统中的最小存储单位,文件和目录的数据都存储在磁盘块中。

我们可以使用结构体模拟磁盘块,其中包含一个数据缓冲区用于存储实际的文件内容。

示例:```ctypedef struct {char data[BLOCK_SIZE];} DiskBlock;```三、文件系统操作函数1. 创建文件:通过调用适当的函数,我们可以在文件系统中创建一个新文件,并为其分配一个唯一的文件名和控制块。

操作系统实验文件管理C代码

操作系统实验文件管理C代码

操作系统实验文件管理C代码Standardization of sany group #QS8QHH-HHGX8Q8-GNHHJ8-HHMHGN##include<stack>using namespace std;#define BLKSIZE 512 .\n");printf("WARNING:ALL DATA ON THIS FILESYSTEM WILL BE LOST!\n");printf("Proceed with Format(Y/N)");scanf("%c", &choice);getchar();if((choice == 'y') || (choice == 'Y')){if((fp=fopen(image_name, "w+b")) == NULL){printf("Can't create file %s\n", image_name);exit(-1);}for(i = 0; i < BLKSIZE; i++)fputc('0', fp);= 0;strcpy, "/");= 'd';strcpy, "/");= 0;= 0;[0] = -1;[1] = -1;fwrite(&inode, sizeof(Inode), 1, fp);= -1;for(i = 0; i < 31; i++)fwrite(&inode, sizeof(Inode), 1, fp); for(i = 0; i < BLKNUM*BLKSIZE; i++)fputc('\0', fp);fclose(fp);n", file_name);printf("This filesystem not exist, it will be create!\n");format();login();}while(!feof(fp)){fread(&user, sizeof(User), 1, fp);n");flag = 1;fclose(fp);break;}}if(flag == 0) break;}while(flag);n", image_name);exit(-1);}num = -1;}n");exit(-1);}bitmap[i] = '1';if((fp=fopen(image_name, "r+b")) == NULL){printf("Can't open file %s\n", image_name);exit(-1);}fseek(fp, i, SEEK_SET);fputc('1', fp);fclose(fp);return i;}ength;add0 = inode_array[num].address[0];if(len > 512)add1 = inode_array[num].address[1];if((fp = fopen(image_name, "r+b")) == NULL){printf("Can't open file %s.\n", image_name);exit(-1);}fseek(fp, BLKSIZE+INODESIZE*INODENUM +add0*BLKSIZE, SEEK_SET);ch = fgetc(fp);for(i=0; (i < len) && (ch != '\0') && (i < 512); i++){temp[i] = ch;ch = fgetc(fp);}if(i >= 512){fseek(fp,BLKSIZE+INODESIZE*INODENUM+add1*BLKSIZE, SEEK_SET);ch = fgetc(fp);for(; (i < len) && (ch != '\0'); i++){temp[i] = ch;ch = fgetc(fp);}}temp[i] = '\0';fclose(fp);}ddress[0];len = inode_array[num].length;if((fp = fopen(image_name, "r+b")) == NULL){printf("Can't open file %s.\n", image_name);exit(-1);}fseek(fp, BLKSIZE+INODESIZE*INODENUM+add0*BLKSIZE, SEEK_SET);for(i=0; (i<len)&&(temp[i]!='\0')&&(i < 512); i++)fputc(temp[i], fp);if(i == 512){add1 = inode_array[num].address[1];fseek(fp, BLKSIZE+INODESIZE*INODENUM+add1*BLKSIZE, SEEK_SET); for(; (i < len) && (temp[i] != '\0'); i++)fputc(temp[i], fp);}fputc('\0', fp);fclose(fp);}num == 0)strcpy(path,;else{strcpy(path,;m=0;n=inum_cur;while(m != inum_cur){while(inode_array[n].iparent != m){n = inode_array[n].iparent;}strcat(path,"/");strcat(path,inode_array[n].file_name);m = n;n = inum_cur;}}printf("[%s]$",path);}或者 cd dir1)void cd(void){int i;if(argc != 2){printf("Command cd must have two args. \n");return ;if(!strcmp(argv[1], ".."))inum_cur = inode_array[inum_cur].iparent;else{for(i = 0; i < INODENUM; i++)if((inode_array[i].inum>0)&&(inode_array[i].type=='d')&&(inode_array[i].iparent==inum_cur)&& !strcmp(inode_array[i].file_name,argv[1])&&!strcmp(inode_array[i].user_name,)break;if(i == INODENUM)printf("This directory isn't exsited.\n");elseinum_cur = i;}\n");return ;}num> 0) &&(inode_array[i].iparent == inum_cur)&&!strcmp(inode_array[i].user_name,){if(inode_array[i].type == 'd'){dcount++;printf("%-20s<DIR>\n", inode_array[i].file_name); }else{fcount++;bcount+=inode_array[i].length;printf("%-20s%12d bytes\n",inode_array[i].file_name,inode_array[i].length);}}printf("\n %d file(s)%11d bytes\n",fcount,bcount);printf(" %d dir(s) %11d bytesFreeSpace\n",dcount,1024*1024-bcount);}\n");return ;}num < 0) break;if(i == INODENUM){printf("Inode is full.\n");exit(-1);}inode_array[i].inum = i;strcpy(inode_array[i].file_name, argv[1]);inode_array[i].type = 'd';strcpy(inode_array[i].user_name,;inode_array[i].iparent = inum_cur;inode_array[i].length = 0;save_inode(i);}\n");return ;}for(i = 0; i < INODENUM; i++){if((inode_array[i].inum > 0) &&(inode_array[i].type == 'f') &&!strcmp(inode_array[i].file_name, argv[1])) {printf("This file is exsit.\n");return ;}}for(i = 0; i < INODENUM; i++)if(inode_array[i].inum < 0) break;if(i == INODENUM){printf("Inode is full.\n");exit(-1);}inode_array[i].inum = i;strcpy(inode_array[i].file_name, argv[1]);inode_array[i].type = 'f';strcpy(inode_array[i].user_name, ;inode_array[i].iparent = inum_cur;inode_array[i].length = 0;save_inode(i);}\n");return ;}for(i = 0; i < INODENUM; i++)if((inode_array[i].inum > 0) &&(inode_array[i].type == 'f') &&!strcmp(inode_array[i].file_name,argv[1])&&!strcmp(inode_array[i].user_name,)break;if(i == INODENUM)printf("The file you want to open doesn't exsited.\n");return ;}inum = i;printf("Please input open mode:(1: read, 2: write, 3: read and write):");scanf("%d", &mode);getchar();if((mode < 1) || (mode > 3)){printf("Open mode is wrong.\n");return;}for(i = 0; i < FILENUM; i++)if(file_array[i].inum < 0) break;if(i == FILENUM)printf("The file table is full, please close some file.\n");return ;}filenum = i;file_array[filenum].inum = inum;strcpy(file_array[filenum].file_name, inode_array[inum].file_name);file_array[filenum].mode = mode;printf("Open file %s by ", file_array[filenum].file_name);if(mode == 1) printf("read only.\n");else if(mode == 2) printf("write only.\n");else printf("read and write.\n");}\n");return;}for(i = 0; i < FILENUM; i++)if((file_array[i].inum > 0) &&!strcmp(file_array[i].file_name,argv[1]))break;if(i == FILENUM){printf("Open %s first.\n", argv[1]);return ;}else if(file_array[i].mode == 2){printf("Can't read %s.\n", argv[1]);return ;}inum = file_array[i].inum;printf("The length of %s:%d.\n", argv[1], inode_array[inum].length);if(inode_array[inum].length > 0){read_blk(inum);for(i = 0; (i < inode_array[inum].length) && (temp[i] != '\0'); i++) printf("%c", temp[i]);}}\n");return ;}for(i = 0; i < FILENUM; i++)if((file_array[i].inum>0)&&!strcmp(file_array[i].file_name,argv[1])) break;if(i == FILENUM){printf("Open %s first.\n", argv[1]);return ;}else if(file_array[i].mode == 1){printf("Can't write %s.\n", argv[1]);return ;}inum = file_array[i].inum;printf("The length of %s:%d\n", inode_array[inum].file_name, inode_array[inum].length);if(inode_array[inum].length == 0){i=0;inode_array[inum].address[0] = get_blknum();printf("Input the data(CTRL+Z to end):\n");while(i<1023&&(temp[i]=getchar())!=EOF) i++;temp[i]='\0';length=strlen(temp)+1;inode_array[inum].length=length;if(length > 512)inode_array[inum].address[1] = get_blknum();save_inode(inum);write_blk(inum);}elseprintf("This file can't be written.\n");}\n");return ;}for(i = 0; i < FILENUM; i++)if((file_array[i].inum > 0) &&!strcmp(file_array[i].file_name, argv[1])) break;if(i == FILENUM){printf("This file doesn't be opened.\n");return ;}else{file_array[i].inum = -1;printf("Close %s success!\n", argv[1]);}}num = -1;if(inode_array[i].length > 0){release_blk(inode_array[i].address[0]);if(inode_array[i].length >= 512)release_blk(inode_array[i].address[1]);}save_inode(i);}\n");return ;}int n,t,i;stack<int> istk;for(i = 0; i < INODENUM; i++)num >=0) &&(inode_array[i].iparent == inum_cur)&& (!strcmp(inode_array[i].file_name,argv[1]))&&(!strcmp(inode_array[i].user_name,)){n=inode_array[i].inum;break;}if(i==INODENUM) puts("Directory ERROR");else{(n);while(!()){t=();();del(t);for(i = 0; i < INODENUM; i++)if((inode_array[i].inum >=0) &&(inode_array[i].iparent == t)) (i);}}}// 功能: 退出当前用户(logout)void logout(){printf("Do you want to exit this user(y/n)");scanf("%c", &choice);getchar();if((choice == 'y') || (choice == 'Y')){printf("\nCurrent user has exited!\n");login();}return ;}// 功能: 退出文件系统(quit)void quit(){printf("Do you want to exist(y/n):");scanf("%c", &choice);getchar();if((choice == 'y') || (choice == 'Y')) exit(0);}// 功能: 显示错误void errcmd(){printf("Command Error\n");}//清空内存中存在的用户名void free_user(){int i;for(i=0;i<10;i++)[i]='\0';}// 功能: 循环执行用户输入的命令, 直到logout// "help", "cd", "dir", "mkdir", "creat", "open","read", "write", "close", "delete", "logout", "clear", "format","quit"void command(void){char cmd[100];system("cls");do{pathset();gets(cmd);switch(analyse(cmd)){case 0:help(); break;cd(); break;case 2:dir(); break;case 3:mkdir(); break; case 4:create(); break; case 5:open(); break; case 6:read(); break;case 7:write(); break;case 8:close(); break;delet(); break;case 10:logout();break;case 11:system("cls");break; case 12:format();init();free_user();login();break;case 13:quit(); break;case 14:errcmd(); break;default:break; }}while(1);}// 主函数int main(void){login();init();command();return 0;}。

操作系统文件管理模拟代码

操作系统文件管理模拟代码

temp=new filenode;
if(recent->child)
//判断下方是否有文件
{
temp=recent->child;
while(temp->next && (strcmp(temp->filename,filename)!=0&&temp|| temp->isdir==0))
temp=temp->next; if(strcmp(temp->filename,filename)!=0||temp->isdir==0)
}
else
{
ttemp=recent->child;
while(ttemp->next)
{
ttemp=ttemp->next;
if(strcmp(ttemp->filename,temp->filename)==0&&ttemp->isdir==0)
实验名称:
文件管理
姓名: 学号:
{ printf("该文件已存在!");
}
else
{
ttemp=recent->child;
if(strcmp(ttemp->filename,temp->filename)==0&&ttemp->isdir==1)
{ printf("该目录已存在!\n");
//这个位置进行二次比对
return 1;
}
while(ttemp->next) {
实验名称:
文件管理
姓名: 学号:
第1页

操作系统实验文件管理C++代码

操作系统实验文件管理C++代码

操作系统实验文件管理C++代码#include #include #include #include #includeusing namespace std;#define BLKSIZE 512 #define BLKNUM 512 #define INODESIZE 32 #define INODENUM 32 #define FILENUM 8//用户typedef struct {// 数据块的大小 // 数据块的块数 // i节点的大小 // i节点的数目 // 打开文件表的数目char user_name[10]; // 用户名 char password[10]; // 密码 } User; //i节点 typedef struct { short inum; // 文件i节点号 charfile_name[10]; // 文件名 char type; // 文件类型 char user_name[10]; // 文件所有者 short iparent; // 父目录的i节点号 short length; // 文件长度 short address[2]; // 存放文件的地址 } Inode;//打开文件表 typedef struct {short inum; // i节点号 char file_name[10]; // 文件名 short mode; // 读写模式(1:read, 2:write, // 3:read and write) } File_table;// 申明函数 void login(void); void init(void);int analyse(char *); void save_inode(int); int get_blknum(void); void read_blk(int); void write_blk(int); void release_blk(int); void pathset(); void del(int);// 用户命令处理函数 void help(void); void cd(void); void dir(void); void mkdir(void); void creat(void); void open(void); void read(void); void write(void); void close(void); void delet(void); void logout(void); void command(void); void quit();//main.cpp文件//#include \//定义全局变量 char choice; int argc; // 用户命令的参数个数 char*argv[5]; // 用户命令的参数 int inum_cur; // 当前目录 chartemp[2*BLKSIZE]; // 缓冲区 User user; // 当前的用户 char bitmap[BLKNUM]; // 位图数组Inode inode_array[INODENUM]; // i节点数组 File_tablefile_array[FILENUM]; // 打开文件表数组 char image_name[10] = \// 文件系统名称 FILE *fp; // 打开文件指针//创建映像hd,并将所有用户和文件清除 void format(void) { int i;Inode inode; printf(\ printf(\ printf(\ scanf(\getchar(); if((choice == 'y') || (choice == 'Y')){ if((fp=fopen(image_name, \ { printf(\ exit(-1); } for(i = 0; i。

操作系统文件管理实验代码

操作系统文件管理实验代码

//利用交‎互式命令实‎现树型目录‎结构和文件‎管理,同时‎利用位示图‎表示外存的‎分配情况,‎新建文件时‎分配必要的‎空间,模拟‎文件分配表‎记录文件在‎外存上的存‎储方式。

了‎解系统对文‎件的操作。

‎//在文‎件中保存目‎录内容,创‎建文件或子‎目录可以用‎命令行命令‎:MD、C‎D、RD、‎M K(创建‎文件)、D‎E L(删除‎文件)和D‎I R‎#incl‎u de<i‎o stre‎a m>#‎i nclu‎d e<st‎d lib.‎h>#i‎n clud‎e<tim‎e.h>‎#incl‎u de <‎l ocal‎e.h> ‎//#‎i nclu‎d e<st‎r ing>‎usin‎g nam‎e spac‎e std‎;//‎#defi‎n e be‎g insi‎z e 5‎#defi‎n e LE‎N GTH ‎3typ‎e def ‎s truc‎t{‎i nt d‎a ta[L‎E NGTH‎];}I‎n dire‎o ne;‎t yped‎e f st‎r uct‎{In‎d ireo‎n e * ‎f irst‎[LENG‎T H];‎}Indi‎r etwo‎;typ‎e def ‎s truc‎t{‎I ndir‎e two ‎* sec‎o nd[L‎E NGTH‎];}I‎n dire‎t hree‎;typ‎e def ‎s truc‎t Nod‎e{‎i nt b‎e gin[‎b egin‎s ize]‎;In‎d ireo‎n e * ‎o ne;‎Indi‎r etwo‎* tw‎o;I‎n dire‎t hree‎* th‎r ee;‎}Mixt‎a b;‎t yped‎e f st‎r uct ‎N ODE‎{ch‎a r na‎m e[50‎];i‎n t ty‎p e;//‎是文件还是‎目录i‎n t si‎z e;//‎如果是文件‎给出大小‎stru‎c t NO‎D E *n‎e xt;/‎/兄弟结点‎str‎u ct N‎O DE *‎sub;‎//子节点‎str‎u ct N‎O DE *‎fath‎e r;//‎父亲节点‎Mixt‎a b * ‎t able‎;}FC‎B;//‎文件控制块‎FCB ‎* roo‎t;FC‎B * p‎r esen‎t;FC‎B * f‎i ndin‎g;ch‎a r st‎r ingn‎a me[3‎00];‎i nt B‎i tmap‎[16][‎16];/‎/位示图‎i nt l‎e ftbi‎t=0;‎v oid ‎I nita‎l l()‎{in‎t i,j‎;sr‎a nd( ‎t ime(‎N ULL)‎);‎f or(i‎=0;i<‎16;i+‎+){‎//初始化‎位示图‎for(‎j=0;j‎<16;j‎++)‎{‎Bitm‎a p[i]‎[j]=r‎a nd()‎%2;‎}}‎roo‎t=(FC‎B *)m‎a lloc‎(size‎o f(FC‎B));‎strc‎p y(ro‎o t->n‎a me,"‎\\");‎roo‎t->ty‎p e=0;‎roo‎t->si‎z e=0;‎roo‎t->ne‎x t=NU‎L L;‎r oot-‎>fath‎e r=ro‎o t;‎r oot-‎>sub=‎N ULL;‎for‎(i=0;‎i<16;‎i++)‎{‎f or(j‎=0;j<‎16;j+‎+)‎{‎i f(Bi‎t map[‎i][j]‎==0)‎{‎l‎e ftbi‎t++;‎}‎}‎}}/‎/判断分配‎外存时候是‎不是足够‎i nt J‎u dgee‎n ough‎(int ‎n){‎if(l‎e ftbi‎t>=n)‎re‎t urn ‎1;e‎l se r‎e turn‎0;}‎//添加‎时候用v‎o id A‎d dpoi‎n t(FC‎B * f‎){‎F CB *‎temp‎;if‎(pres‎e nt->‎s ub==‎N ULL)‎{‎pres‎e nt->‎s ub=f‎;}‎else‎{‎temp‎=pres‎e nt->‎s ub;‎whi‎l e(te‎m p->n‎e xt!=‎N ULL)‎{‎te‎m p=te‎m p->n‎e xt; ‎}‎temp‎->nex‎t=f;‎f->‎n ext=‎N ULL;‎}}‎//删除‎时候用v‎o id D‎e lpoi‎n t(FC‎B *f)‎{F‎C B * ‎t emp=‎p rese‎n t->s‎u b;‎i f(te‎m p==f‎){‎pre‎s ent-‎>sub=‎t emp-‎>next‎;d‎e lete‎(f);‎}e‎l se‎{w‎h ile(‎t emp-‎>next‎!=f)‎{‎tem‎p=tem‎p->ne‎x t;‎}‎t emp-‎>next‎=f->n‎e xt;‎del‎e te(f‎);}‎}//‎查找是不是‎已经存在‎i nt I‎s exis‎t(cha‎r ary‎[],in‎t x)‎{FC‎B * t‎e mp;‎if(p‎r esen‎t->su‎b==NU‎L L)‎{r‎e turn‎0;‎}el‎s e{‎te‎m p=pr‎e sent‎->sub‎;w‎h ile(‎t emp!‎=NULL‎){‎i‎f((!s‎t rcmp‎(temp‎->nam‎e,ary‎))&&(‎t emp-‎>type‎==x))‎{‎‎f indi‎n g=te‎m p;‎re‎t urn ‎1;‎}‎temp‎=temp‎->nex‎t;‎}r‎e turn‎0;‎}}/‎/创建目录‎void‎Mdli‎s t()‎{ch‎a r li‎s tnam‎e[50]‎;ci‎n>>li‎s tnam‎e;F‎C B * ‎t emp;‎if(‎I sexi‎s t(li‎s tnam‎e,0))‎{‎cout‎<<"子目‎录或文件"‎<<lis‎t name‎<<"已存‎在。

操作系统实训C++文件管理系统

操作系统实训C++文件管理系统

目录1 设计目的 (1)2 设计内容 (1)3 设计步骤 (1)3.1 开发平台 (1)3.1.1 开发环境介绍 (1)3.1.2 开发界面截图 (2)3.2 详细设计 (2)3.2.1 算法说明 (2)3.2.2 系统流程图 (4)3.3 运行与测试 (4)3.3.1 运行测试 (4)3.3.2 异常处理测试 (7)3.4使用说明 (9)4 设计总结 (10)5 附录 (10)1 设计目的(用小3号黑体,并留出上下间距为:段前0.5行,段后0.5行)《操作系统概论》学习已经快结束了,通过本课程,了解了操作系统的发展,组成,处理器管理,存储管理,文件管理,设备管理,并发进程等相关知识。

理论必须与实际联系,才能理解的更加深刻,所以进行了这次课程设计,制作一个文件模拟系统的程序,加深对相关知识的理解与运用。

2 设计内容本设计应完成以下要求:1.设计一个10个用户的文件系统,用户至少有Create、delete、open、close、read、write等文件操作命令。

2.程序采用多级文件目录管理,仅可能模拟文件存取的全过程。

3 设计步骤3.1 开发平台3.1.1 开发环境介绍我们采用了C语言来并在Visual Studio 2005平台实现。

.NET Framework是生成、运行下一代应用程序和XML Web Services的内部Windows组件。

它简化了分布式Internet环境中的应用程序开发,由公共语言运行库(CLR)和.NET Framework类库两个组件构成。

Visual Studio 2005 是微软公司开发的集成开发环境,支持C、C++、VB、J#、C#等多种开发语言,界面友好,并有自动补全代码功能,便于调式,是当前最流行的.NET Framework开发工具。

安装Visual Studio 2005的系统要求:硬件需求描述处理器Pentium3级600MHZ以上处理器RAM Windows XP Professional至少为160MB硬盘对于Visual C#.NET、Visual ,需要600MB硬盘空间,安装驱动器上需要1.5GB磁盘空间视频800*600像素,256色(建议:增强色16位)鼠标Microsoft鼠标或兼容的指针设备3.1.2 开发界面截图3.2 详细设计3.2.1 算法说明用户登录时要输入用户名和密码,如果正确则进入初始界面,默认只有十个用户。

文件管理系统源代码

文件管理系统源代码

文件管理系统一、实验目的通过设计一个多用户文件系统,了解操作系统中文件的组织与管理,熟悉文件管理所用的数据结构,加深对文件系统内部功能实现过程的理解。

二、实验内容1.用C语言或C++语言设计一个最多包括N个用户的多用户文件系统,约定每个用户最多保存M个文件。

同时限制一个用户在进入系统后,最多打开L个文件。

2.系统应具备一定的健壮性。

即能够检查用户所输入命令的正确性,出错时显示出必要的信息。

另外,对文件需设置必要的保护措施。

3.文件目录结构采用两级目录结构:主文件目录和用户文件目录#include"io.h"#include"conio.h"#include"stdio.h"#include"stdlib.h"#include"malloc.h"#include"string.h"#include"ctype.h"#define N 30 /*用户数*/#define M 20 /*一个用户可保存M个文件*/#define L 5 /*用户只能一次打开L个文件*/typedef struct MFD /*主文件目录*/{char username[100];char password[100];FILE fp; /*文件指针*/}MFD;///////////typedef struct UFD /*用户文件目录*/{char filename[256];char protect; /*保护码*/int length; /*文件长度*/}UFD;//////////typedef struct OFD /*打开文件目录*/{char filename[256];char opencode; /*打开保护码*/int fp; /*读写指针*/}OFD;//////////typedef struct COMM /*命令串*/{char string[256]; /*命令*/struct COMM *next;/*后继指针*/}COMM;////////////MFD mainfd[N]; /*主文件目录数组*/UFD userfd[M]; /*用户文件目录数组*/OFD openfd[L]; /*打开文件目录数组*/////////COMM*command; /*命令串指针*/char username[10];int usernum,savenum,opennum;int workfile;void init();void init_ufd(char *username);/*初始化用户文件目录*/ void mesg(char *str); /*消息*/char *getpass(); /*设置口令函数声明*/ char *getuser(); /*设置用户函数声明*/ COMM *readcommand(); /*读命令串函数声明*/ void login(); /*用户登录*/void logout(); /*用户注销*/void setpass(); /*设置口令*/void create(); /*创建文件*/void mydelete(); /*删除文件*/void myread(); /*读文件*/void myopen(); /*打开文件*/void myclose(); /*关闭文件*/void mywrite(); /*写文件*/void help(); /*帮助*/void dir(); /*列文件目录*/void mycopy(); /*复制文件*/void myrename(); /*重命名文件名*//////////////void main(){init();for(;;){readcommand();if(strcmp(command->string,"create")==0)create();else if(strcmp(command->string,"delete")==0)mydelete();else if(strcmp(command->string,"open")==0)myopen();else if(strcmp(command->string,"close")==0)myclose();else if(strcmp(command->string,"read")==0)myread();else if(strcmp(command->string,"write")==0)mywrite();else if(strcmp(command->string,"copy")==0)mycopy();else if(strcmp(command->string,"rename")==0)myrename();else if(strcmp(command->string,"login")==0)login();else if(strcmp(command->string,"setpass")==0)setpass();else if(strcmp(command->string,"logout")==0)logout();else if(strcmp(command->string,"help")==0)help();else if(strcmp(command->string,"dir")==0)dir();else if(strcmp(command->string,"exit")==0)break;elsemesg("Bad command!");}}///////////////////void init(){FILE *fp;char tempname[20],temppass[20];int i=0;usernum=0;savenum=0;opennum=0;strcpy(username,"");if((fp=fopen("mainfile.txt","r"))!=NULL){while(!feof(fp)){strcpy(tempname,"");fgets(tempname,20,fp);if(strcmp(tempname,"")!=0){fgets(temppass,20,fp);tempname[strlen(tempname)-1]='\0';temppass[strlen(tempname)-1]='\0';strcpy(mainfd[usernum].username,tempname);strcpy(mainfd[usernum].password,tempname);usernum++;}}fclose(fp);}}///////////////////////void init_ufd(char *username)/*初始化用户文件目录*/{FILE *fp;char tempfile[100],tempprot;int templength;savenum=0;opennum=0;workfile=-1;if((fp=fopen(username,"w+"))!=NULL){while(!feof(fp)){strcpy(tempfile,"");fgets(tempfile,50,fp);if(strcmp(tempfile,"")!=0){fscanf(fp,"%c",&tempprot);fscanf(fp,"%d",&templength);tempfile[strlen(tempfile)-1]='\0';strcpy(userfd[savenum].filename,tempfile);userfd[savenum].protect=tempprot;userfd[savenum].length=templength;savenum++;fgets(tempfile,50,fp);}}}fclose(fp);}////////////////////void mesg(char *str){printf("\n %s\n",str);}////////////////////////////char *getuser(){char username[20];char temp;int i;username[0]='\0';for(i=0;i<10;){while(!kbhit());temp=getch();if(isalnum(temp)||temp=='_'||temp==13){username[i]=temp;if(username[i]==13){username[i]='\0';break;}putchar(temp);i++;username[i]='\0';}}return(username);}///////////////////char *getpass(){char password[20];char temp;int i;password[0]='\0';for(i=0;i<10;){while(!kbhit());temp=getch();if(isalnum(temp)||temp=='_'||temp==13){password[i]=temp;if(password[i]==13){password[i]='\0';break;}putchar('*');i++;password[i]='\0';}}return(password);}///////////////COMM *readcommand(){char temp[256];char line[256];int i,end;COMM *newp,*p;command=NULL;strcpy(line,"");while(strcmp(line,"")==0){printf("\nc:\\>");gets(line);}for(i=0;i<=strlen(line);i++){if(line[i]==' ')i++;end=0;while(line[i]!='\0'&&line[i]!=' '){temp[end]=line[i];end++;i++;}if(end>0){temp[end]='\0';newp=(COMM *)malloc(sizeof(COMM *));strcpy(newp->string,temp);newp->next=NULL;if(command==NULL)command=newp;else{p=command;while(p->next!=NULL)p=p->next;p->next=newp;}}}p=command;return(command);}/////////////////////////////void login() /*用户注册*/{FILE *fp;int i;char password[20],confirm[20],tempname[20];if(command->next==NULL){printf("\n User Name:");strcpy(tempname,getuser());}else if(command->next->next!=NULL){mesg("Too many parameters!");return;}elsestrcpy(tempname,command->next->string);for(i=0;i<usernum;i++)if(strcmp(mainfd[i].username,tempname)==0)break; /*从mainfd表中查找要注册的用户*/ if(i>=usernum) /*新用户*/{printf("\n new user account,enter your password twice!");printf("\n Password:");strcpy(password,getpass());/*输入口令且返回之*/printf("\n Password:");strcpy(confirm,getpass()); /*第二次输入口令*/if(strcmp(password,confirm)==0)/*用户数不能超过N*/{if(usernum>=N)mesg("Create new account false!number of user asscount limited.\n login fasle!");else{strcpy(mainfd[usernum].username,tempname);/*把新用户和口令填入mainfd中*/strcpy(mainfd[usernum].password,password);usernum++;strcpy(username,tempname);mesg("Create a new user!\n login success!");init_ufd(username); /*初始化用户文件目录*/fp=fopen("mainfile.txt","w+"); /*把新用户填入mainfile.txt文件中*/for(i=0;i<usernum;i++){fputs(mainfd[i].username,fp);fputs("\n",fp);fputs(mainfd[i].password,fp);fputs("\n",fp);}fclose(fp);}}else{mesg("Create new account false! Error password.");mesg("login false!");}}else{printf("\n Password:");strcpy(password,getpass());if(strcmp(mainfd[i].password,password)!=0)mesg("Login false! Error password.");else{mesg("Login success!");strcpy(username,tempname);init_ufd(username);}}}/////////////////////////void logout() /*用户注销*/{if(command->next!=NULL)mesg("Too many parameters!");else if(strcmp(username,"")==0)mesg("No user login!");else{strcpy(username,"");opennum=0;savenum=0;workfile=-1;mesg("User logout!");}}////////////////////void setpass() /*修改口令*/{int i=0;FILE *fp;char oldpass[20],newpass[20],confirm[20];if(strcmp(username,"")==0)mesg("No user login!");else{printf("\n Old password:");strcpy(oldpass,getpass());for(int i=0;i<usernum;i++){if(strcmp(mainfd[i].username,username)==0)break;}if(strcmp(mainfd[i].password,oldpass)!=0)mesg("Old password error!");else{printf("\n New password:");strcpy(newpass,getpass());printf("\n Confirm password:");strcpy(confirm,getpass());if(strcmp(newpass,confirm)!=0)mesg("Password not change! confirm different.");else{strcpy(mainfd[i].password,newpass);mesg(" Password change !");fp=fopen("mainfile.txt","w+");for(i=0;i<usernum;i++){fputs(mainfd[i].username,fp);fputs("\n",fp);fputs(mainfd[i].password,fp);fputs("\n",fp);}fclose(fp);}}}}////////////////void create(){int i=0;FILE *fp;if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next!=NULL)mesg("Too many parameters!");else{for(i=0;i<savenum;i++){if(strcmp(userfd[i].filename,command->next->string)==0)break;}if(i<savenum)mesg("Error! the file already existed!");else if(savenum>=M)mesg("Error! connot create file! number of files limited!");else{strcpy(userfd[savenum].filename,command->next->string);userfd[i].protect='r';userfd[i].length=rand();savenum++;mesg("Create file success!");fp=fopen(username,"w+");for(i=0;i<savenum;i++){fputs(userfd[i].filename,fp);fputs("\n",fp);fprintf(fp,"%c\n%d\n",userfd[i].protect,userfd[i].length);}fclose(fp);}}}/////////////////void mydelete() /*删除*/{int i=0;int tempsave=0;FILE *fp;if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next!=NULL)mesg("Too many parameters!");else{for(i=0;i<savenum;i++){if(strcmp(userfd[i].filename,command->next->string)==0)break;}if(i>=savenum)mesg("Error! the file not existed!");else{tempsave=i;for(i=0;i<opennum;i++){if(strcmp(command->next->string,openfd[i].filename)==0)break;}if(i>=opennum)mesg("File not open");////////////////////////////////////////////else{if(tempsave==savenum-1)savenum--;else{for(;tempsave<savenum-1;tempsave++){strcpy(userfd[tempsave].filename,userfd[tempsave+1].filename);userfd[tempsave].protect=userfd[tempsave+1].protect;userfd[tempsave].length=userfd[tempsave+1].length;}savenum--;}mesg("Delete file success!");fp=fopen(username,"w+");for(i=0;i<savenum;i++){fputs(userfd[i].filename,fp);fputs("\n",fp);fprintf(fp,"%c\n%d\n",userfd[i].protect,userfd[i].length);}fclose(fp);}}}}//////////////////void myread() /*读*/{int i=0;int tempsave=0;char tempfile[100];if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next!=NULL)mesg("Too many parameters!");elsestrcpy(tempfile,command->next->string);for(i=0;i<savenum;i++){if(strcmp(tempfile,userfd[i].filename)==0)break;}if(i>=savenum)mesg("File not existed!");else{tempsave=i;for(i=0;i<opennum;i++){if(strcmp(tempfile,openfd[i].filename)==0)break;}if(i>=opennum)mesg("File not opened");else{if(userfd[tempsave].length<1000)printf("\n The file size is %d KB",userfd[tempsave].length);else if(userfd[tempsave].length==1000)printf("\n The file size is 1000 KB");elseprintf("\n The file size is %d,%d KB",userfd[tempsave].length/1000,userfd[tempsave].length%1000);mesg("File read");}}}}/////////////////void myopen()/*打开*/{int i=0;int type=0;char tempcode;char tempfile[100];if(strcmp(username,"")==0)mesg("No user login!");else if(command->next==NULL)mesg("Too few parameters!");{strcpy(tempfile,"");tempcode='r';if(strcmp(command->next->string,"/r")==0){tempcode='r';type=1;}else if(strcmp(command->next->string,"/w")==0){tempcode='w';type=1;}else if(strcmp(command->next->string,"/d")==0){tempcode='d';type=1;}else if(command->next->string[0]=='/')mesg("Error! /r/w/d request!");else if(command->next->next!=NULL)mesg("Too many parameters!");elsestrcpy(tempfile,command->next->string);if(type==1){if(command->next->next!=NULL){if(command->next->next->next!=NULL)mesg("Too many parameters!");elsestrcpy(tempfile,command->next->next->string);}elsemesg("Too few parameters!");}if(strcmp(tempfile,"")){for(i=0;i<savenum;i++){if(strcmp(tempfile,userfd[i].filename)==0)break;}if(i>=savenum)mesg("File not existed!");else{for(i=0;i<opennum;i++){if(strcmp(tempfile,openfd[i].filename)==0)break;}if(i<opennum){mesg("File already opened!");if(openfd[i].opencode!=tempcode){openfd[i].opencode=tempcode;mesg("File permission changed!");}}else if(opennum>=L){mesg("Error! connot open file! number of opened files limited!");}else{strcpy(openfd[opennum].filename,tempfile);openfd[opennum].opencode=tempcode;workfile=opennum;opennum++;mesg("File open success!");}}}}}///////////////////////void myclose()/*关闭*/{int i=0;int tempsave=0;char tempfile[100];if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next!=NULL)mesg("Too many parameters!");else{strcpy(tempfile,command->next->string);for(i=0;i<savenum;i++){if(strcmp(tempfile,userfd[i].filename)==0)break;}if(i>=savenum)mesg("File not existed!");else{for(i=0;i<opennum;i++){if(strcmp(tempfile,openfd[i].filename)==0)break;}if(i>=opennum)mesg("File not opened");else{if(i==opennum-1)opennum--;else{for(;i<opennum-1;i++){strcpy(openfd[i].filename,openfd[i+1].filename);openfd[i].opencode=openfd[i+1].opencode;}opennum--;}mesg("Close file success!");}}}}/////////////////////////void mywrite()/*写*/{int i=0;int tempsave=0;char tempfile[100];if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next!=NULL)mesg("Too many parameters!");else{strcpy(tempfile,command->next->string);for(i=0;i<savenum;i++){if(strcmp(tempfile,userfd[i].filename)==0)break;}if(i>=savenum)mesg("File not existed!");else{tempsave=i;for(i=0;i<opennum;i++){if(strcmp(tempfile,openfd[i].filename)==0)break;}if(i>=opennum)mesg("File not opened");else{mesg("File write");int tt=rand();if(userfd[tempsave].length<=1000)printf("\n The file size from %d KB to %d KB",userfd[tempsave].length,userfd[tempsave].length+tt);/* else if(userfd[tempsave].lenght=1000)printf("\n The file size from 1000 KB");*/elseprintf("\n The file size form %d,%d KB to %d,%d KB",userfd[tempsave].length/1000,userfd[tempsave].length%1000,userfd[tempsave].length+tt/10 00,userfd[tempsave].length+tt%1000);userfd[tempsave].length=userfd[tempsave].length+tt;}}}}///////////////////void help()/*帮助*/{static char *cmd[]={"login","setpass","logout","create","open","read","write","close","delete","dir","help","exit","copy","rename"};static char *cmdhlp[]={"aommand format: login [<username>]","command format:setpass","command format:logout","command format:create <filename>","command format:open [/r/w/d] <filename>","command format:read <filename>","command format:write <filename>","command format:close <filename>","command format:delete <filename>","command format:dir [/u/o/f]","command format:help [<command>]","command format:exit","command format:copy <source filename> <destination filename>","command format:rename <old filename> <new filename>"};static char *detail[]={"explain:user login in the file system.","explain:modify the user password.","explain:user logout the file system.","explain:creat a new file.","explain:/r -- read only [deflaut]\n\t /w -- list opened files \n\t /d --read,modify and delete.","explain:read the file.","explain:modify the file.","explain:close the file.","explain:delete the file.","explain:/u -- list the user account\n\t /0 -- list opened files\n\t /f --list user file[deflaut].","explain:<command> -- list the command detail format and explain.\n\t [deflaut] list the command.","explain:exit from the file sysytem.","explain:copy from one file to another file.","explain:modify the file name."};int helpnum=14;int i=0;if(command->next==NULL){mesg(cmdhlp[10]);mesg(detail[10]);mesg("step 1: login");printf("\t if old user then login,if user not exist then create new user");mesg("step 2: open the file for read(/r),write(/w)or delete(/d)");printf("\t you can open one or more files.one command can open one file");mesg("step 3: read,write or delete some one file");printf("\t you can operate one of the opened files.one command can open one file");mesg("step 4: close the open file");printf("\t you can close one of the opened files.one command can open one file");mesg("step 5: user logout.close all the user opened files");printf("\n command list:");for(i=0;i<helpnum;i++){if(i%4==0)printf("\n");printf(" %-10s",cmd[i]);}}else if(command->next->next!=NULL)mesg("Too many parameters!");else{for(i=0;i<helpnum;i++){if(strcmp(command->next->string,cmd[i])==0)break;}if(i>=helpnum)mesg("the command not existed!");else{mesg(cmdhlp[i]);mesg(detail[i]);}}}//////////////////////void dir()/*列目录文件*/{int i=0;int type=0;char tempcode;if(strcmp(username,"")==0)mesg("No user login!");else{if(command->next==NULL){tempcode='f';}else{if(strcmp(command->next->string,"/u")==0){tempcode='u';}else if(strcmp(command->next->string,"/o")==0){tempcode='o';}else if(strcmp(command->next->string,"/f")==0){tempcode='f';}else if(command->next->string[0]=='/')mesg("Error! /u/o/f request!");else if(command->next->next!=NULL)mesg("Too many parameters!");}if('u'==tempcode){printf("list the user account\n");printf("usename\n");for(i=0;i<usernum;i++){printf("%s\n",mainfd[i].username);}}else if('f'==tempcode){printf("list opened files\n");printf("filename length protect\n");for(i=0;i<savenum;i++){printf("%s%s%d%s%s%c\n",userfd[i].filename," ",userfd[i].length,"KB"," ",userfd[i].protect);}}else if('o'==tempcode){printf("list user files\n");printf("filename opencode\n");for(i=0;i<opennum;i++){printf("%s%s%c\n",openfd[i].filename," ",openfd[i].opencode);}}}}/////////////////////////void mycopy()/*复制*/{char sourfile[256],destfile[256];int i=0,j=0,temp=0;FILE *fp;char tempchar;if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next==NULL)mesg("Too few parametets!");else if(command->next->next->next!=NULL)mesg("Too many parameters!");else{strcpy(sourfile,command->next->string);strcpy(destfile,command->next->next->string);for(i=0;i<savenum;i++){if(strcmp(sourfile,userfd[i].filename)==0)break;}temp=i;if(i>=savenum)printf("\n the source file not eixsted!");else{for(i=0;i<opennum;i++){if(strcmp(sourfile,openfd[i].filename)==0)break;}if(i>=opennum)printf("\n the source file not opened!");else{for(j=0;j<opennum;j++){if(strcmp(destfile,openfd[i].filename)==0)break;}if(j<opennum)mesg("Error! the destination file opened,you must close it first.");else{for(j=0;j<savenum;j++){if(strcmp(destfile,userfd[i].filename)==0)break;}if(j<savenum){mesg("Warning! the destination file exist!");printf("\n Are you sure to recover if ? [Y/N]");while(!kbhit());tempchar=getch();if(tempchar=='N'||tempchar=='n')mesg("Cancel! file not copy.");else if(tempchar=='Y'||tempchar=='y'){mesg("File copy success!file recovered!");userfd[j].length=userfd[i].length;userfd[j].protect=userfd[i].protect;fp=fopen(username,"w+");for(i=0;i<savenum;i++){fputs(userfd[i].filename,fp);fputs("\n",fp);fprintf(fp,"%C\n%d\n",userfd[i].protect,userfd[i].length);}fclose(fp);}}else if(savenum>=M)mesg("copy false! file total limited.");else{strcpy(userfd[savenum].filename,destfile);userfd[savenum].length=userfd[temp].length;userfd[savenum].protect=userfd[temp].protect;savenum++;fp=fopen(username,"w+");for(i=0;i<savenum;i++){fputs(userfd[i].filename,fp);fputs("\n",fp);fprintf(fp,"%c\n%d\n",userfd[i].protect,userfd[i].length);}fclose(fp);mesg("File copy success!");}}}}}}///////////////////////void myrename()/*文件重命名*/{char oldfile[256],newfile[256];int i=0,temp=0;if(strcmp(username,"")==0)mesg("No user lgoin!");else if(command->next==NULL)mesg("Too few parametets!");else if(command->next->next==NULL)mesg("Too few parametets!");else if(command->next->next->next!=NULL)mesg("Too many parameters!");else{strcpy(oldfile,command->next->string);strcpy(newfile,command->next->next->string);for(i=0;i<savenum;i++){if(strcmp(oldfile,userfd[i].filename)==0)break;}temp=i;if(temp>=savenum)printf("\n the source file not eixsted!");else if(temp!=i&&i<savenum){printf("\n newfile and the existing files is the same name, please re-naming!");}else{for(i=0;i<opennum;i++){if(strcmp(oldfile,openfd[i].filename)==0)break;}if(i>=opennum)printf("\n the source file not opened!");else if(strcmp(oldfile,newfile)==0){printf("Rename false! oldfile and newfile can not be the same.");}else{strcpy(openfd[i].filename,newfile);strcpy(userfd[temp].filename,newfile);mesg("Rename file success!\n");}}}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

. #include <stdio.h>#include <stdlib.h>#include <conio.h>#include <string.h>#include<stack>using namespace std;#define BLKSIZE 512 // 数据块的大小#define BLKNUM 512 // 数据块的块数#define INODESIZE 32 // i节点的大小#define INODENUM 32 // i节点的数目#define FILENUM 8 // 打开文件表的数目//用户typedef struct{char user_name[10]; // 用户名char password[10]; // 密码} User;//i节点typedef struct{short inum; // 文件i节点号char file_name[10]; // 文件名char type; // 文件类型char user_name[10]; // 文件所有者short iparent; // 父目录的i节点号short length; // 文件长度short address[2]; // 存放文件的地址} Inode;//打开文件表typedef struct{short inum; // i节点号char file_name[10]; // 文件名short mode; // 读写模式(1:read, 2:write,// 3:read and write) } File_table;// 申明函数void login(void);void init(void);int analyse(char *); void save_inode(int); int get_blknum(void); void read_blk(int); void write_blk(int); void release_blk(int); void pathset();void del(int);// 用户命令处理函数void help(void);void cd(void);void dir(void);void mkdir(void);void creat(void);void open(void);void read(void);void write(void);void close(void);void delet(void);void logout(void); void command(void); void quit();//main.cpp文件//#include "head.h"//定义全局变量char choice;int argc; // 用户命令的参数个数char *argv[5]; // 用户命令的参数int inum_cur; // 当前目录char temp[2*BLKSIZE]; // 缓冲区User user; // 当前的用户char bitmap[BLKNUM]; // 位图数组Inode inode_array[INODENUM]; // i节点数组File_table file_array[FILENUM]; // 打开文件表数组char image_name[10] = "data.dat"; // 文件系统名称FILE *fp; // 打开文件指针//创建映像hd,并将所有用户和文件清除void format(void){int i;Inode inode;printf("Will be to format filesystem...\n");printf("WARNING:ALL DATA ON THIS FILESYSTEM WILL BE LOST!\n"); printf("Proceed with Format(Y/N)?");scanf("%c", &choice);getchar();if((choice == 'y') || (choice == 'Y')){if((fp=fopen(image_name, "w+b")) == NULL){printf("Can't create file %s\n", image_name);exit(-1);}for(i = 0; i < BLKSIZE; i++)fputc('0', fp);inode.inum = 0;strcpy(inode.file_name, "/");inode.type = 'd';strcpy(er_name, "/");inode.iparent = 0;inode.length = 0;inode.address[0] = -1;inode.address[1] = -1;fwrite(&inode, sizeof(Inode), 1, fp);inode.inum = -1;for(i = 0; i < 31; i++)fwrite(&inode, sizeof(Inode), 1, fp);for(i = 0; i < BLKNUM*BLKSIZE; i++)fputc('\0', fp);fclose(fp);// 打开文件user.txtif((fp=fopen("user.txt", "w+")) == NULL){printf("Can't create file %s\n", "user.txt");exit(-1);}fclose(fp);printf("Filesystem created successful.Please first login!\n");}return ;}// 功能: 用户登陆,如果是新用户则创建用户void login(void){char *p;int flag;char user_name[10];char password[10];char file_name[10] = "user.txt";do{printf("login:");gets(user_name);printf("password:");p=password;while(*p=getch()){if(*p == 0x0d){*p='\0'; //将输入的回车键转换成空格break;}printf("*"); //将输入的密码以"*"号显示p++;}flag = 0;if((fp = fopen(file_name, "r+")) == NULL){printf("\nCan't open file %s.\n", file_name);printf("This filesystem not exist, it will be create!\n");format();login();}while(!feof(fp)){fread(&user, sizeof(User), 1, fp);// 已经存在的用户, 且密码正确if(!strcmp(er_name, user_name) &&!strcmp(user.password, password)){fclose(fp);printf("\n");return ;}// 已经存在的用户, 但密码错误else if(!strcmp(er_name, user_name)){printf("\nThis user is exist, but password is incorrect.\n");flag = 1;fclose(fp);break;}}if(flag == 0) break;}while(flag);// 创建新用户if(flag == 0){printf("\nDo you want to creat a new user?(y/n):");scanf("%c", &choice);gets(temp);if((choice == 'y') || (choice == 'Y')){strcpy(er_name, user_name);strcpy(user.password, password);fwrite(&user, sizeof(User), 1, fp);fclose(fp);return ;}if((choice == 'n') || (choice == 'N'))login();}}// 功能: 将所有i节点读入存void init(void){int i;if((fp = fopen(image_name, "r+b")) == NULL){printf("Can't open file %s.\n", image_name);exit(-1);}// 读入位图for(i = 0; i < BLKNUM; i++)bitmap[i] = fgetc(fp);// 显示位图// 读入i节点信息for(i = 0; i < INODENUM; i++)fread(&inode_array[i], sizeof(Inode), 1, fp);// 显示i节点// 当前目录为根目录inum_cur = 0;// 初始化打开文件表for(i = 0; i < FILENUM; i++)file_array[i].inum = -1;}// 功能: 分析用户命令, 将分析结果填充argc和argv// 结果: 0-13为系统命令, 14为命令错误int analyse(char *str){int i;char temp[20];char *ptr_char;char *syscmd[]={"help", "cd", "dir", "mkdir", "create", "open", "read", "write","close", "delet", "logout", "clear","format","quit"};argc = 0;for(i = 0, ptr_char = str; *ptr_char != '\0'; ptr_char++){if(*ptr_char != ' '){while(*ptr_char != ' ' && (*ptr_char != '\0'))temp[i++] = *ptr_char++;argv[argc] = (char *)malloc(i+1);strncpy(argv[argc], temp, i);argv[argc][i] = '\0';argc++;i = 0;if(*ptr_char == '\0') break;}}if(argc != 0){for(i = 0; (i < 14) && strcmp(argv[0], syscmd[i]); i++);return i;}elsereturn 14;}// 功能: 将num号i节点保存到hd.datvoid save_inode(int num){if((fp=fopen(image_name, "r+b")) == NULL){printf("Can't open file %s\n", image_name);exit(-1);}fseek(fp, BLKNUM +num*sizeof(Inode), SEEK_SET);fwrite(&inode_array[num], sizeof(Inode), 1, fp);fclose(fp);}// 功能: 申请一个数据块int get_blknum(void){int i;for(i = 0; i < BLKNUM; i++)if(bitmap[i] == '0') break;// 未找到空闲数据块if(i == BLKNUM){printf("Data area is full.\n");exit(-1);}bitmap[i] = '1';if((fp=fopen(image_name, "r+b")) == NULL){printf("Can't open file %s\n", image_name);exit(-1);}fseek(fp, i, SEEK_SET);fputc('1', fp);fclose(fp);return i;}// 功能: 将i节点号为num的文件读入tempvoid read_blk(int num){int i, len;char ch;int add0, add1;len = inode_array[num].length;add0 = inode_array[num].address[0];if(len > 512)add1 = inode_array[num].address[1];if((fp = fopen(image_name, "r+b")) == NULL){printf("Can't open file %s.\n", image_name);exit(-1);}fseek(fp, BLKSIZE+INODESIZE*INODENUM +add0*BLKSIZE, SEEK_SET);ch = fgetc(fp);for(i=0; (i < len) && (ch != '\0') && (i < 512); i++){temp[i] = ch;ch = fgetc(fp);}if(i >= 512){fseek(fp,BLKSIZE+INODESIZE*INODENUM+add1*BLKSIZE, SEEK_SET);ch = fgetc(fp);for(; (i < len) && (ch != '\0'); i++){temp[i] = ch;ch = fgetc(fp);}}temp[i] = '\0';fclose(fp);}// 功能: 将temp的容输入hd的数据区void write_blk(int num){int i, len;int add0, add1;add0 = inode_array[num].address[0];len = inode_array[num].length;if((fp = fopen(image_name, "r+b")) == NULL){printf("Can't open file %s.\n", image_name);exit(-1);}fseek(fp, BLKSIZE+INODESIZE*INODENUM+add0*BLKSIZE, SEEK_SET);for(i=0; (i<len)&&(temp[i]!='\0')&&(i < 512); i++)fputc(temp[i], fp);if(i == 512){add1 = inode_array[num].address[1];fseek(fp, BLKSIZE+INODESIZE*INODENUM+add1*BLKSIZE, SEEK_SET);for(; (i < len) && (temp[i] != '\0'); i++)fputc(temp[i], fp);}fputc('\0', fp);fclose(fp);}// 功能: 释放文件块号为num的文件占用的空间void release_blk(int num){FILE *fp;if((fp=fopen(image_name, "r+b")) == NULL){printf("Can't open file %s\n", image_name);exit(-1);}bitmap[num] = '0';fseek(fp, num, SEEK_SET);fputc('0', fp);fclose(fp);}// 功能: 显示帮助命令void help(void){printf("command: \n\help --- show help menu \n\clear --- clear the screen \n\cd --- change directory \n\mkdir --- make directory \n\create --- create a new file \n\open --- open a exist file \n\read --- read a file \n\write --- write something to a file \n\close --- close a file \n\delet --- delete a exist file or directory \n\ format --- format a exist filesystem \n\logout --- exit user \n\quit --- exit this system\n");}//设置文件路径void pathset(){char path[50];int m,n;if(inode_array[inum_cur].inum == 0)strcpy(path,er_name);else{strcpy(path,er_name);m=0;n=inum_cur;while(m != inum_cur){while(inode_array[n].iparent != m){n = inode_array[n].iparent;}strcat(path,"/");strcat(path,inode_array[n].file_name);m = n;n = inum_cur;}}printf("[%s]$",path);}// 功能: 切换目录(cd .. 或者cd dir1)void cd(void){int i;if(argc != 2){printf("Command cd must have two args. \n");return ;}if(!strcmp(argv[1], ".."))inum_cur = inode_array[inum_cur].iparent;else{for(i = 0; i < INODENUM; i++)if((inode_array[i].inum>0)&&(inode_array[i].type=='d')&&(inode_array[i].iparent==inum_cur)&&!strcmp(inode_array[i].file_name,argv[1])&&!strcmp(inode_array[i].user_name,er_name))break;if(i == INODENUM)printf("This directory isn't exsited.\n");elseinum_cur = i;}}// 功能: 显示当前目录下的子目录和文件(dir)void dir(void){int i;int dcount=0,fcount=0;short bcount=0;if(argc != 1){printf("Command dir must have one args. \n");return ;}// 遍历i节点数组, 显示当前目录下的子目录和文件名for(i = 0; i < INODENUM; i++)if((inode_array[i].inum> 0) &&(inode_array[i].iparent == inum_cur)&&!strcmp(inode_array[i].user_name,er_name)) {if(inode_array[i].type == 'd'){dcount++;printf("%-20s<DIR>\n", inode_array[i].file_name);}else{fcount++;bcount+=inode_array[i].length;printf("%-20s%12d bytes\n", inode_array[i].file_name,inode_array[i].length);}}printf("\n %d file(s)%11d bytes\n",fcount,bcount);printf(" %d dir(s) %11d bytes FreeSpace\n",dcount,1024*1024-bcount);}// 功能: 在当前目录下创建子目录(mkdir dir1)void mkdir(void){int i;if(argc != 2){printf("command mkdir must have two args. \n");return ;}// 遍历i节点数组, 查找未用的i节点for(i = 0; i < INODENUM; i++)if(inode_array[i].inum < 0) break;if(i == INODENUM){printf("Inode is full.\n");exit(-1);}inode_array[i].inum = i;strcpy(inode_array[i].file_name, argv[1]);inode_array[i].type = 'd';strcpy(inode_array[i].user_name,er_name);inode_array[i].iparent = inum_cur;inode_array[i].length = 0;save_inode(i);}// 功能: 在当前目录下创建文件(creat file)void create(void){int i;if(argc != 2){printf("command creat must have two args. \n");return ;}for(i = 0; i < INODENUM; i++){if((inode_array[i].inum > 0) &&(inode_array[i].type == 'f') &&!strcmp(inode_array[i].file_name, argv[1])) {printf("This file is exsit.\n");return ;}}for(i = 0; i < INODENUM; i++)if(inode_array[i].inum < 0) break;if(i == INODENUM){printf("Inode is full.\n");exit(-1);}inode_array[i].inum = i;strcpy(inode_array[i].file_name, argv[1]);inode_array[i].type = 'f';strcpy(inode_array[i].user_name, er_name);inode_array[i].iparent = inum_cur;inode_array[i].length = 0;save_inode(i);}// 功能: 打开当前目录下的文件(open file1)void open(){int i, inum, mode, filenum;if(argc != 2){printf("command open must have two args. \n");return ;}for(i = 0; i < INODENUM; i++)if((inode_array[i].inum > 0) &&(inode_array[i].type == 'f') &&!strcmp(inode_array[i].file_name,argv[1])&&!strcmp(inode_array[i].user_name,er_name))break;if(i == INODENUM){printf("The file you want to open doesn't exsited.\n");return ;}inum = i;printf("Please input open mode:(1: read, 2: write, 3: read and write):"); scanf("%d", &mode);getchar();if((mode < 1) || (mode > 3)){printf("Open mode is wrong.\n");return;}for(i = 0; i < FILENUM; i++)if(file_array[i].inum < 0) break;if(i == FILENUM){printf("The file table is full, please close some file.\n");return ;}filenum = i;file_array[filenum].inum = inum;strcpy(file_array[filenum].file_name, inode_array[inum].file_name); file_array[filenum].mode = mode;printf("Open file %s by ", file_array[filenum].file_name);if(mode == 1) printf("read only.\n");else if(mode == 2) printf("write only.\n");else printf("read and write.\n");}// 功能: 从文件中读出字符(read file1)void read(){int i, inum;if(argc != 2){printf("command read must have two args. \n");return;}for(i = 0; i < FILENUM; i++)if((file_array[i].inum > 0) &&!strcmp(file_array[i].file_name,argv[1]))break;if(i == FILENUM){printf("Open %s first.\n", argv[1]);return ;}else if(file_array[i].mode == 2){printf("Can't read %s.\n", argv[1]);return ;}inum = file_array[i].inum;printf("The length of %s:%d.\n", argv[1], inode_array[inum].length);if(inode_array[inum].length > 0){read_blk(inum);for(i = 0; (i < inode_array[inum].length) && (temp[i] != '\0'); i++) printf("%c", temp[i]);}}// 功能: 向文件中写入字符(write file1)void write(){int i, inum, length;if(argc != 2){printf("Command write must have two args. \n");return ;}for(i = 0; i < FILENUM; i++)if((file_array[i].inum>0)&&!strcmp(file_array[i].file_name,argv[1])) break;if(i == FILENUM){printf("Open %s first.\n", argv[1]);return ;}else if(file_array[i].mode == 1){printf("Can't write %s.\n", argv[1]);return ;}inum = file_array[i].inum;printf("The length of %s:%d\n", inode_array[inum].file_name, inode_array[inum].length);if(inode_array[inum].length == 0){i=0;inode_array[inum].address[0] = get_blknum();printf("Input the data(CTRL+Z to end):\n");while(i<1023&&(temp[i]=getchar())!=EOF) i++;temp[i]='\0';length=strlen(temp)+1;inode_array[inum].length=length;if(length > 512)inode_array[inum].address[1] = get_blknum();save_inode(inum);write_blk(inum);}elseprintf("This file can't be written.\n");}// 功能: 关闭已经打开的文件(close file1)void close(void){int i;if(argc != 2){printf("Command close must have two args. \n");return ;}for(i = 0; i < FILENUM; i++)if((file_array[i].inum > 0) &&!strcmp(file_array[i].file_name, argv[1])) break;if(i == FILENUM){printf("This file doesn't be opened.\n");return ;}else{file_array[i].inum = -1;printf("Close %s success!\n", argv[1]);}}//回收i节点,有文件则删除文件void del(int i){inode_array[i].inum = -1;if(inode_array[i].length > 0){release_blk(inode_array[i].address[0]);if(inode_array[i].length >= 512)release_blk(inode_array[i].address[1]);}save_inode(i);}//删除子目录树和文件void delet(void){if(argc != 2){printf("Command delete must have two args. \n");return ;}int n,t,i;stack<int> istk;for(i = 0; i < INODENUM; i++)//查找待删除子目录if((inode_array[i].inum >=0) &&(inode_array[i].iparent == inum_cur)&&(!strcmp(inode_array[i].file_name,argv[1]))&&(!strcmp(inode_array[i].user_name,er_name))) {n=inode_array[i].inum;break;}if(i==INODENUM) puts("Directory ERROR");else{istk.push(n);while(!istk.empty()){t=istk.top();istk.pop();del(t);for(i = 0; i < INODENUM; i++)if((inode_array[i].inum >=0) &&(inode_array[i].iparent == t))istk.push(i);}}}// 功能: 退出当前用户(logout)void logout(){printf("Do you want to exit this user(y/n)?");scanf("%c", &choice);getchar();if((choice == 'y') || (choice == 'Y')){printf("\nCurrent user has exited!\n");login();}return ;}// 功能: 退出文件系统(quit)void quit(){printf("Do you want to exist(y/n):");scanf("%c", &choice);getchar();if((choice == 'y') || (choice == 'Y'))exit(0);}// 功能: 显示错误void errcmd(){printf("Command Error!!!\n");}//清空存中存在的用户名void free_user(){int i;for(i=0;i<10;i++)er_name[i]='\0';}// 功能: 循环执行用户输入的命令, 直到logout// "help", "cd", "dir", "mkdir", "creat", "open","read", "write", "close", "delete", "logout", "clear", "format","quit"void command(void){char cmd[100];system("cls");do{pathset();gets(cmd);switch(analyse(cmd)){case 0:help(); break; case 1:cd(); break; case 2:dir(); break; case 3:mkdir(); break; case 4:create(); break; case 5:open(); break; case 6:read(); break; case 7:write(); break; case 8:close(); break; case 9:delet(); break; case 10:logout();break; case 11:system("cls");break;case 12:format();init();free_user();login();break;case 13:quit(); break;case 14:errcmd(); break;default:break;}}while(1);}// 主函数int main(void){login();init();command();return 0;}。

相关文档
最新文档