ExOJ 文件系统 (Cpp)

这道题写的比较乱,主要就是字符串处理问题,因为带有空白字符的一整行字符串无法用scanf读入,而部分OJ又禁用gets函数,所以在这里选择用cin.getline(),然后再分解字符串。

大致思路就是利用结构体数组,其中用0/1分别表示目录or文件,再另设置两个变量用于保存文件/目录名称及其所属目录路。最后根据读入的字符串判断对应操作即可,因为题目已经限制了很多极端条件,所以总体来说这道题只是写着麻烦,但并不难。

#include <cstdio>
#include <iostream>
#include <cstring>
#include <string>
using namespace std; 

struct File {
	int sta;	//0为目录, 1为文件 
	char name[100];
	char fdir[100];
};
int main() {
	int T;
	scanf("%d", &T);
	while (T > 0) {
		int n, tot = 1;
		scanf("%d\n", &n);
		char str[5][109];
		char ch[109];
		File file[109]; 
		file[0].sta = 0;
		strcpy(file[0].name, "root");		//初始化root的目录信息 
		strcpy(file[0].fdir, "###");
		for (int p = 0; p < n; p++) {
			cin.getline(ch, 109, '\n');
			int le = strlen(ch), h = 0, r = 0;
			for (int i = 0; i < le; i++) {		//将一行字符串分解 
				if (ch[i] != ' ') 
					str[h][r++] = ch[i];
				else {
					str[h][r] = '\0';
					h++;
					r = 0;
				}
			}
			str[h][r] = '\0';		//想一下若没有这行代码会发生什么? 
			int len = strlen(str[0]);	//四种字符串长度分别为7 8 9 10 
			int op = len % 7;	//取模
			if (op == 0) {		//LISTDIR
				for (int i = 0; i < tot; i++) 
					if (strcmp(file[i].fdir, str[1]) == 0 && file[i].sta == 0) printf("%s\n", file[i].name); 
			} else if (op == 1) {	//LISTFILE
				for (int i = 0; i < tot; i++)
					if (strcmp(file[i].fdir, str[1]) == 0 && file[i].sta == 1) printf("%s\n", file[i].name); 
			} else if (op == 2) {	//CREATEDIR
				file[tot].sta = 0;
				strcpy(file[tot].name, str[1]);
				strcpy(file[tot].fdir, str[2]);
				tot++;
			} else if (op == 3) {	//CREATEFILE
				file[tot].sta = 1;
				strcpy(file[tot].name, str[1]);
				strcpy(file[tot].fdir, str[2]);
				tot++;
			}
		}
		T--;
	} 
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值