操作系统实验文件管理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;。
文件管理系统源代码
文件管理系统一、实验目的通过设计一个多用户文件系统,了解操作系统中文件的组织与管理,熟悉文件管理所用的数据结构,加深对文件系统内部功能实现过程的理解。
二、实验内容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.实验目的通过一个简单多用户文件系统的设计,加深理解文件系统的内部功能及内部实现 2.实验内容为Linux 系统设计一个简单的二级文件系统。
要求做到以下几点: (1)可以实现下列几条命令(至少4条) login 用户登录 dir列文件目录create 创建文件 delete 删除文件open 打开文件 close 关闭文件 read 读文件 write写文件(2)列目录时要列出文件名、物理地址、保护码和文件长度; (3)源文件可以进行读写保护。
3.实验提示(1)首先应确定文件系统的数据结构:主目录、子目录及活动文件等。
主目录和子目录都以文件的形式存放于磁盘,这样便于查找和修改.(2)用户创建的文件,可以编号存储于磁盘上。
入file0,file1,file2…并以编号作为物理地址,在目录中进行登记。
4.源代码#include<stdio 。
h> #include 〈string.h 〉 #include 〈stdlib 。
h 〉 #define MEM_D_SIZE 1024*1024 //总磁盘空间为1M #define DISKSIZE 1024 //磁盘块的大小1K #define DISK_NUM 1024 //磁盘块数目1K #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 #define MSD 5 //最大子目录数5#define MOFN 5//最大文件深度为5#define MAX_WRITE 1024*128//最大写入文字长度128KBstruct 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]。
简单的文档管理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欢迎使用本院文档管理系统,本系统将为您提供历史案件信息查询,工作学习书籍查阅管理。
操作系统实验参考代码
目录实验一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进程的“一生”。
文件管理系统源代码
文件管理系统一、实验目的通过设计一个多用户文件系统,了解操作系统中文件的组织与管理,熟悉文件管理所用的数据结构,加深对文件系统内部功能实现过程的理解。
二、实验内容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语言实现
一、设计目的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循环的循环条件,一举两得。
操作系统实验(金虎)实验四文件管理源代码
if(flag1==0)//将指针指向申请fat表块数第一块
{
p->f=r;
flag1++;
}
p->length++;
r->next=NULL;
while(t->next!=NULL)
t=t->next;
int i=0,j=0;
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
cout<<map[i][j]<<" ";
cout<<endl;
}
}
void mk()
{
Fname *p,*q,*s;
Fat *r,*t;
q=temp;
s=temp;
t=Ft;
cuur = time(NULL);
strftime(tmp,sizeof(tmp),"%Y-%m-%d %X",localtime(&cuur));//显示时间
int i,j,a=0,num,k=0,flag1=0;
string name;
cin>>name;
cout<<"请输入文件大小:"<<endl;
q=q->brother;
}
}
while(r->file!=NULL) //计算文件所占字节
{
f=r->file->f;
y=r->file->length;
操作系统实训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 算法说明用户登录时要输入用户名和密码,如果正确则进入初始界面,默认只有十个用户。
文件系统模拟实验(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语言中一些常用的文件系统相关的数据结构和函数。
二、文件系统数据结构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++代码
//申明函数
void login(void);
void init(void);
int analyse(char *);
void save_inode(int);
intget_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);
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);
}
return ;
}
//功能:用户登陆,如果是新用户则创建用户
void login(void)
{
char *p;
int flag;
char user_name[10];
char password[10];
char file_name[10] = "user.txt";
操作系统实验文件管理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页
操作系统文件管理实验代码
//利用交互式命令实现树型目录结构和文件管理,同时利用位示图表示外存的分配情况,新建文件时分配必要的空间,模拟文件分配表记录文件在外存上的存储方式。
了解系统对文件的操作。
//在文件中保存目录内容,创建文件或子目录可以用命令行命令:MD、CD、RD、M K(创建文件)、DE L(删除文件)和DI R#inclu de<io strea m>#i nclud e<std lib.h>#in clude<time.h>#inclu de <l ocale.h> //#i nclud e<str ing>using name space std;//#defin e beg insiz e 5#defin e LEN GTH 3type def s truct{i nt da ta[LE NGTH];}In direo ne;t ypede f str uct{Ind ireon e * f irst[LENGT H];}Indir etwo;type def s truct{I ndire two * seco nd[LE NGTH];}In diret hree;type def s truct Node{i nt be gin[b egins ize];Ind ireon e * o ne;Indir etwo* two;In diret hree* thr ee;}Mixta b;t ypede f str uct N ODE{cha r nam e[50];in t typ e;//是文件还是目录in t siz e;//如果是文件给出大小struc t NOD E *ne xt;//兄弟结点stru ct NO DE *sub;//子节点stru ct NO DE *fathe r;//父亲节点Mixta b * t able;}FCB;//文件控制块FCB * root;FCB * pr esent;FCB * fi nding;cha r str ingna me[300];i nt Bi tmap[16][16];//位示图i nt le ftbit=0;v oid I nital l(){int i,j;sra nd( t ime(N ULL));f or(i=0;i<16;i++){//初始化位示图for(j=0;j<16;j++){Bitma p[i][j]=ra nd()%2;}}root=(FCB *)ma lloc(sizeo f(FCB));strcp y(roo t->na me,"\\");root->typ e=0;root->siz e=0;root->nex t=NUL L;r oot->fathe r=roo t;r oot->sub=N ULL;for(i=0;i<16;i++){f or(j=0;j<16;j++){i f(Bit map[i][j]==0){le ftbit++;}}}}//判断分配外存时候是不是足够i nt Ju dgeen ough(int n){if(le ftbit>=n)ret urn 1;el se re turn0;}//添加时候用vo id Ad dpoin t(FCB * f){F CB *temp;if(prese nt->s ub==N ULL){prese nt->s ub=f;}else{temp=prese nt->s ub;whil e(tem p->ne xt!=N ULL){tem p=tem p->ne xt; }temp->next=f;f->n ext=N ULL;}}//删除时候用vo id De lpoin t(FCB *f){FC B * t emp=p resen t->su b;i f(tem p==f){pres ent->sub=t emp->next;de lete(f);}el se{wh ile(t emp->next!=f){temp=temp->nex t;}t emp->next=f->ne xt;dele te(f);}}//查找是不是已经存在i nt Is exist(char ary[],int x){FCB * te mp;if(pr esent->sub==NUL L){re turn0;}els e{tem p=pre sent->sub;wh ile(t emp!=NULL){if((!st rcmp(temp->name,ary))&&(t emp->type==x)){f indin g=tem p;ret urn 1;}temp=temp->next;}re turn0;}}//创建目录voidMdlis t(){cha r lis tname[50];cin>>lis tname;FC B * t emp;if(I sexis t(lis tname,0)){cout<<"子目录或文件"<<list name<<"已存在。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
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);
#define INODESIZE 32// i节点的大小
#define INODENUM 32// i节点的数目
#define FILENUM 8// 打开文件表的数目
//用户
typedef struct
{
char user_name[10];// 用户名
char password[10];// 密码
if(argc != 0)
{
for(i = 0; (i < 14) && strcmp(argv[0], syscmd[i]); i++);
return i;
}
else
return 14;
}
// 功能: 将num号i节点保存到hd.dat
void save_inode(int num)
{
if((fp=fopen(image_name, "r+b")) == NULL)
fputc('\0', fp);
fclose(fp);
// 打开文件user.txt
if((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");
gets(temp);
if((choice == 'y') || (choice == 'Y'))
{
strcpy(er_name, user_name);
strcpy(user.password, password);
fwrite(&user, sizeof(User), 1, fp);
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);
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include<stack>
using namespace std;
#define BLKSIZE 512// 数据块的大小
#define BLKNUM 512// 数据块的块数
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;
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();
{
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++)
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++)
short address[2]; // 存放文件的地址
} Inode;
பைடு நூலகம்//打开文件表
typedef struct
{
short inum;// i节点号
char file_name[10]; // 文件名
short mode;// 读写模式(1:read, 2:write,
// 3:read and 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'))
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);
} File_table;
// 申明函数
void login(void);
void init(void);
int analyse(char *);
void save_inode(int);
intget_blknum(void);
void read_blk(int);
void write_blk(int);
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"
//定义全局变量
fclose(fp);
return ;
}
if((choice == 'n') || (choice == 'N'))
login();
}
}
// 功能: 将所有i节点读入内存
void init(void)
{
int i;
if((fp = fopen(image_name, "r+b")) == NULL)
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");
// 结果: 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",