操作系统实验文件管理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++代码
#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;}。
实验设备管理系统设计C源代码
源代码#include <iostream>#include <cstdlib>#include <string>#include <fstream>#include <sstream>using namespace std;class Node //结点类,用于存放客户的各种信息{publiclong id; //实验设备编号string name; //名称string type //随便类型string suoshushiyanshi; //实验设备所属实验室string buytime; //购买时间string price; //价格string amount; //库存量string shengchanriqi; //生产日期string shiyongshouming; //使用寿命string weight; //重量Node *next; //指向下一结点的指针Node(long id=000,string nname="noname",string ntype="unkown".string nsuoshushiyanshi="unknow",string nbuytime="unknow",string nprice="unknow",string namount="unknow",string nshengchanriqi="unkown",string nshiyongshouming="unknow",string nweight="unknow");//构造函数,初始化变量};class Link//Link 类,把数据以链表的形式存储,链表的每个结点为一个Node对象{private:Node *head;//链表的头指针,为Node对象类型的指针public:Link();//构造函数,初始化变量bool link IsEmpty();//判断链表是否为空void linkInsert(Node *newnode);//向链表中插入新的结点bool linkDelete(int nid);//从链表中删除的结点void linkClear();//清空链表中数据void linkView();//查看链表中数据Node* linkFind(int nid);//在链表中查找id为nid结点,返回指向该结点的指针Node* getHead();//获取头指针};Node::Node(long nid,string nname,string ntype,string nsuoshushiyanshi,string nbuytime,string nprice,string namount,string nshengchanriqi,string nshiyongshouming,string nweight){id=nid;name=nname;type=ntypesuoshushiyanshi=nsuoshushiyanshi;buytime=nbuytime;price=nprice;amount=namount;shengchanriqi=nshengchanriqi;shiyongshouming=nshiyongshouming;weight= nweight;next=NULL;}Link::Link() //构造函数,初始化链表为空{head=NULL;}bool Link::linkIsEmpty() //判断链表是否为空,空则返回true{return(head==NULL);}void Link::linkInsert(Node *newnode)//按id值从小到大的顺序,插入新的结点{Node *pl;if(!head)//链表为空的情况head=newnode;else if((head->id)>(newnode->id))//插入到第一个结点的情况{newnode->next=head;head=newnode;}else//插入到第二个及以后情况{pl=head;while(1){if(!(pl->next)){pl->next=newnode;break;}else if((pl->next)->id>newnode->id){newnode->next=pl ->next;pl ->next=newnode;break;}pl=pl ->next;}}}bool Link::linkDelete(int nid)//删除结点,成功则返回true {Node *p;if(head==NULL)//链表为空的情况return false;if(head->id==nid)//删除的为第一个结点的情况{head=head->next;return true}p=head;while(p->next)//删除的为第二个及以后的情况{if((p->next)->id==nid){p->next=(p->next)->next;return true;}p=p->next;}return false;}void Link::linkClear()//清空链表{head=NULL;}Node* Link::linkFind(int nid)//查找id 值为nid的结点,返回该结的的指针{Node *p=head; //没找到符合条件的结点的话,返回的指针值为NULL while(p){if(p->id==nid)break;elsep=p->next;}return p;}void Link::linkView()//显示链表数据{Node *p=head;while(p){cout<<"实验设备编号:"<<p->id<<endl;cout<<"名称:"<<p->name<<endl;cout<<"类型:"<<p->type<<endl;cout<<"所属实验室:"<<p->suoshushiyanshi<<endl;cout<<"购买时间:"<<p->buytime<<endl;cout<<"价格:"<<p->price<<endl;cout<<"库存量:"<<p->amount<<endl;cout<<"生产日期:"<<p->shenchanriqi<<endl;cout<<"使用寿命:"<<p->shiyongshouming<<endl;cout<<"重量:"<<p->weight<<endl;cout<<"*******************************************************"<<endl;p=p->next;}}Node* Link::getHead(){return head;}//类Shebei,用于包装Link类及菜单操作class Shebei{private:Link clink;//Link 对象成员bool k;//记录数据是否被修改public:Shebei();void ShebeiClear();void ShebeiInsert();void ShebeiDelete();void ShebeiFind();void ShebeiModify();void ShebeiView();void ShebeiLoad();void ShebeiSave();void Exit();//退出程序void showMenu();//显示菜单void showTip();//显示操作提示void doMenu(char n);//执行相应菜单项功能};Shebei:: Shebei(){Link();//调用成员对象的构造函数ShebeiLoad();从文件中读取数据,创建链表k=false;//设置数据被修改}void Shebei::ShebeiClear()//清空设备记录{clink.linkClear();cout<<"成功清空设备信息记录!"<<endl;}void Shebei::ShebeiInsert()//插入设备记录{Node *p=new Node();cout<<"请输入设备编号:";cin>>p->id;cout<<"请输入名称:";cin>>p->name;cout<<"请输入类型:";cin>>p->type;cout<<"请输入所属实验室:";cin>>p->suoshushiyanshi;cout<<"请输入购买时间:";cin>>p->buytime;cout<<"请输入价格:";cin>>p->price;cout<<"请输入库存量:";cin>>p->amount;cout<<"请输入生产日期:";cin>>p->shengchanriqi;cout<<"请输入设备重量:";cin>>p->weight;if(!clink.linkFind(p->id))判断设备信息是否存在{clink.linkInsert(p);k=true;}elsecout<<"设备编号为"<<p->id<<"的设备已存在,插入失败! "<<endl; }void Shebei::ShebeiDelete()//删除设备记录{long i;if(clink.linkIsEmpty())//链表为空的情况cout<<"没有设备记录! "<<endl;else{cout<<"请输入设备编号:";cin>>i;if(clink.linkDelete(i)){cout<<"成功删除编号为"<<i<<"的实验记录!"<<endl;k=true;}elsecout<<"没有找到编号为"<<i<<"的设备!"<<endl;}}void Shebei::ShebeiFind()//查找某编号的设备记录{long n;Node *p;if(clink.linkIsEmpty())//链表为空的情况cout<<"没有设备记录!"<<endl;else{cout<<"请输入要查找的设备的编号:";cin>>n;p=clink.linkFind(n);//获得找到的结点的指针if(p)//指针值不为NULL时{cout<<"实验设备编号:"<<p->id<<endl;cout<<"名称:"<<p->name<<endl;cout<<"类型:"<<p->type<<endl;cout<<"所属实验室:"<<p->suoshushiyanshi<<endl;cout<<"购买时间:"<<p->buytime<<endl;cout<<"价格:"<<p->price<<endl;cout<<"库存量:"<<p->amount<<endl;cout<<"生产日期:"<<p->shengchanriqi<<endl;cout<<"使用寿命:"<<p->shiyongshouming<<endl;cout<<"重量:"<<p->weight<<endl;}else//指针值为NULL时cout<<"没有找到编号为"<<n<<"的设备记录!"<<endl;}}void Shebei::ShebeiModify()//修改某编号的设备信息{long n;Node *p;if(clink.linkIsEmpty())//链表为空的情况cout<<"没有设备记录!"<<endl;else{cout<<"请输入要修改的设备的编号:";cin>>n;p=clink.linkFind(n);//获得找到的结点的指针if(p)//指针值不为NULL时{cout<<"实验设备编号:"<<p->id<<endl;cout<<"名称:"<<p->name<<endl;cout<<"类型:"<<p->type<<endl;cout<<"所属实验室:"<<p->suoshushiyanshi<<endl;cout<<"购买时间:"<<p->buytime<<endl;cout<<"价格:"<<p->price<<endl;cout<<"库存量:"<<p->amount<<endl;cout<<"生产日期:"<<p->shengchanriqi<<endl;cout<<"使用寿命:"<<p->shiyongshouming<<endl;cout<<"重量:"<<p->weight<<endl;cout<<"请输入新的设备信息"<<endl;cout<<"请输入设备编号:";cin>>p->id;cout<<"请输入名称:";cin>>p->name;cout<<"请输入类型:";cin>>p->type;cout<<"请输入所属实验室:";cin>>p->suoshushiyanshi;cout<<"请输入购买时间:";cin>>p->buytime;cout<<"请输入价格:";cin>>p->price;cout<<"请输入库存量:";cin>>p->amount;cout<<"请输入生产日期:";cin>>p->shengchanriqi;cout<<"请输入设备重量:";cin>>p->weight;}else//指针值为NULL时cout<<"没有找到编号为"<<n<<"的设备记录! "<<endl;}}void Shebei::ShebeiView()//显示所有设备的记录{if(clink.linkIsEmpty())cout<<"没有设备记录! "<<endl;elseclink.linkView();}void Shebei::ShebeiLoad()//从文件中读入数据,创建链表{Node *p;long nid;ifstream infile("data.txt");if(!infile)cerr<<"错误:数据文件不能打开!\n";elsewhile(infile>>nid)//读取客户,直到读空{p=new Node();p->id=nid;infile>>p->name>>" "; //读取名称infile>>p->type>>" ";infile>>p->suoshushiyanshi>>" ";infile>>p->buytime>>" ";infile>>p->price>>" ";infile>>p->amount>>" ";infile>>p->shengchanriqi>>" ";infile>>p->weight>>" ";clink.linkInsert(p);}infile.close(); //关闭文件}void Shebei::ShebeiSave()//将数据保存到文件{Node *p=clink.getHead();ofstream outfile("data.txt");if(!outfile)cerr<<"错误:数据文件不能打开!\n";else{while(p){outfile<<p->id<<" "<<p->name<<" "<<p->type<<""<<p->suoshushiyanshi<<" "<<p->buytime<<" "<<p->price<<" "<<p->amount<<" "<<p->shengchanriqi<<" "<<p->weight<<" "<<endl;p=p->next;}k=false;cout<<"保存成功!"<<endl;}}void Shebei::Exit(){char s='Y';if(k)//判断数据是否修改{cout<<"数据已经改变,是否保存?(y/n):"cin>>s;if(s=='Y'lls=='Y')ShebeiSave();}cout<<"已安全退出,";system("pause");exit(0);}void Shebei::showMenu()cout<<"\t\t*********************************************"<<endl; cout<<"\t\t* 实验室设备管理系统*"<<endl;cout<<"\t\t* *"endl;cout<<"\t\t* 1--清除所有设备信息*"endl;cout<<"\t\t* *"endl;cout<<"\t\t* 2--添加:增加一个设备到设备信息中*"endl;cout<<"\t\t* *"endl;cout<<"\t\t* 3--删除:删除指定设备数据*"endl;cout<<"\t\t* *"endl;cout<<"\t\t* 4--查找:根据设备数据查找设备信息*"endl;cout<<"\t\t* *"endl;cout<<"\t\t* 5--修改:修改指定设备信息*"endl; cout<<"\t\t* *"endl; cout<<"\t\t* 6--显示:在屏幕上显示所有设备的消息*"endl; cout<<"\t\t* *"endl; cout<<"\t\t* 7--存储:将设备信息保存在一个文件中*"endl; cout<<"\t\t* *"endl; cout<<"\t\t* 0--退出:安全的退出本系统*"endl;cout<<"\t\t********************************************"endl;}void Shebei::showTip(){cout<<endl;cout<<"*****************操作完成***************"<<endl;cout<<"***************选择0--7继续************"<<endl;cout<<"请选择:";}void Shebei::doMenu(char n){switch(n){case'1':ShebeiClear();break;case'2':ShebeiInsert();break;case'3':ShebeiDelete();break;case'4':ShebeiFind();break;case'5':ShebeiModify();break;case'6':ShebeiView();break;case'7':ShebeiSave();break;case'0':Exit();break;default:cout<<"输入错误!";}}int main(){Shebei c;char i='9';c.showMenu();cout<<"欢迎来到实验室设备管理系统:"<<endl;cout<<"请选择你需要的服务:";while(1){cin>>i;system("cls"); //清除屏幕c.showMenu();c.doMenu(i);c.showTip();}return 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代码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;}。
学生成绩管理系统(c语言结构体以及文件操作)实验报告
int sumS;
}STUDENT;
//函数功能:利用循环输入学生的学号姓名以及成绩等信息。
int InputScore(STUDENT stu[],int m)
{
int i,j,n;
printf(”请输入参加考试的人数:");
scanf("%d”,&n);
for(i=0;i〈n;i++)
{
printf(”请输入第%d个学生的信息:学号,姓名,成绩(数学、英语,物理)\n”,i+1);
scanf("%ld”,&stu[i].studentID);
scanf("%s",stu[i]。studen{
scanf(”%d",&stu[i]。score[j]);
** 1、录入每个学生的学号,姓名,和各科考试成绩!**
**2、计算每个学生的总分和平均分!**
**3、按每个学生的总分和平均分从高到低排出名次表!**
**4、按姓名的字典顺序排出成绩!**
**5、按姓名查询学生学生排名和考试成绩!**
** 6、输出每个学生的学号,姓名,各科成绩!**
**7、将每个学生的信息写入文件!**
四、错误提示界面
***************************************
*****请先录入学生信息和成绩****
***************************************
五、函数代码
1、主函数
/*编程:孟令鑫131110412
时间:2013年12月24日
内容;结构体实现学生成绩管理系统*/
操作系统文件管理模拟代码
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)。
*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) &&
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.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"); } return ; } // 功能: 用户登陆,如果是新用户则创建用户 void login(void) {
#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 #define INODENUM 32 #define FILENUM 8
// 当前的用户
char bitmap[BLKNUM]; // 位图数组
Inode inode_array[INODENUM]; // i 节点数组
File_table file_array[FILENUM]; // 打开文件表数组
char image_name[10] = "data.dat"; // 文件系统名称
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();
{
short inum;
// 文件 i 节点号
char file_name[10]; // 文件名
char type;
// 文件类型
char user_name[10]; // 文件所有者
short iparent;
// 父目录的 i 节点号
short length;
// 文件长度
short address[2]; // 存放文件的地址
} Inode;
//打开文件表
typedef struct{shFra bibliotekrt inum;
// i 节点号
char file_name[10]; // 文件名
short mode;
// 读写模式(1:read, 2:write,
//
3:read and write)
} File_table;
// 申明函数 void login(void); void init(void);
!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");
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++)
// 数据块的大小 // 数据块的块数
// i 节点的大小 // i 节点的数目
// 打开文件表的数目
//用户 typedef struct {
char user_name[10]; char password[10]; } User;
// 用户名 // 密码
//i 节点
typedef struct
//main.cpp 文件
//#include "head.h"
//定义全局变量
char choice;
int
argc; // 用户命令的参数个数
char *argv[5]; // 用户命令的参数
int
inum_cur;
// 当前目录
char temp[2*BLKSIZE]; // 缓冲区
User user;
"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; } else return 14; } // 功能: 将 num 号 i 节点保存到 hd.dat void save_inode(int num) { if((fp=fopen(image_name, "r+b")) == NULL) { printf("Can't open file %s\n", image_name); exit(-1); }
// 初始化打开文件表 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",