C 语言单层目录程序

2025年1月7日 | 阅读 4 分钟

在操作系统中,目录可以以多种方式组织。单级目录结构是其中最直接的一种。这种组织方式只有根目录和用户两个组成部分。根目录中有一个主入口目录,只放置一个文件。该系统的主根目录放置系统中的所有文件。所有系统文件都保存在这些主文件夹中。主目录中不能有任何子目录。这种框架非常容易实现,并且使得搜索非常简单。然而,它的一个显著缺点是不能有两个同名的文件。一个系统有数百个这样的文件,所有这些文件都将包含在一个根目录中。因此,即使文件数量很少,目录的大小也会非常庞大。

此程序的功能包括插入文件、删除文件、搜索文件以及显示现有文件

示例

让我们通过一个程序来演示 C 语言中的单级目录

输出

Enter the directory name: myfolder
choose the option 
1:Inserting the file
2:Displaying All Files
3:Deleting the File
4:Searching the File
5:Exit
>>1
Enter the File name: hii.txt
choose the option 
1:Inserting the file
2:Displaying All Files
3:Deleting the File
4:Searching the File
5:Exit
>>1
Enter the File name: newone.c
choose the option 
1:Inserting the file
2:Displaying All Files
3:Deleting the File
4:Searching the File
5:Exit
>>1
Enter the File name: lastone.txt
choose the option 
1:Inserting the file
2:Displaying All Files
3:Deleting the File
4:Searching the File
5:Exit
>>2
+------------------------+
 Directory	files    | 
+------------------------+
 myfolder
 		hii.txt
 		newone.c
 		lastone.txt
+------------------------+
 choose the option 
1:Inserting the file
2:Displaying All Files
3:Deleting the File
4:Searching the File
5:Exit
>>4
Enter the file name to be searched:newone.c
The particular File is found at position 2
 choose the option 
1:Inserting the file
2:Displaying All Files
3:Deleting the File
4:Searching the File
5:Exit
>>3
Enter the file name to be deleted: lastone.txt
lastone.txt is deleted.
choose the option 
1:Inserting the file
2:Displaying All Files
3:Deleting the File
4:Searching the File
5:Exit
>>2
+------------------------+
 Directory	files    | 
+------------------------+
 myfolder
 		hii.txt
 		newone.c
+------------------------+
 choose the option 
1:Inserting the file
2:Displaying All Files
3:Deleting the File
4:Searching the File
5:Exit
>>5

说明

  1. 包含所需的头文件
    • 使用 h 头文件进行输入输出操作
    • 用于处理字符串的函数,使用 h
    • 使用 h 进行退出函数
  2. 创建一个名为“file”的“结构体”
    • char fileName[15][20]:一个二维数组,用于存储目录的文件名。它存储的每个文件名最长可达 15 个字符。
    • char dirName[10]一个字符数组,用于存储目录名(最长 10 个字符)。
    • int fno一个整数,用于记录目录中的文件数量。
  3. 将变量 dir、in 声明为全局变量。整数变量 in 在多个函数中使用,而 dir 是 file 结构体的一个实例。
  4. 定义几个函数
    • Insertin_File():用户可以使用 Insertin_File() 方法向目录中添加文件名。它会要求用户输入,并将文件名添加到目录结构中。
    • DisplayFiles():DisplayFiles() 格式化目录中的文件名,并与目录名一起显示它们。
    • Deleting_File():Deleting_File() 函数允许用户通过提供文件名从目录中删除特定文件。它通过名称查找文件,如果找到则将其删除。
    • Searching_File():用户可以使用 Searching_File() 函数通过文件名在目录中搜索文件。如果找到文件,则显示其位置。
  5. 在 main() 函数中
    1. dir.fno(文件数)的初始值设置为 0。
    2. 向用户请求目录名,并将其存储在 dir.dir_Name 中。
    3. 显示一个菜单,并使用 while 循环反复提示用户选择一个操作。
    4. 在循环内部读取用户的选择 (op),然后使用 switch 语句根据选择执行相应的函数。

情况 1:添加文件到目录中。

情况 2:显示目录中的文件。

情况 3:目录中删除文件。

情况 4:检查目录中是否存在文件。

情况 5:使用 exit(0) 结束程序。

此代码提供了一个简单的命令行界面来控制目录中的文件。它是一个用于教育目的的基本示例,因为它缺少错误处理,并且在程序运行之间不维护数据。