#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <io.h>
#include <direct.h> 

void getcmd(char* source,char* dest)
{
	int i=0;
	int j=0;
	while(source[i]!=' ')
	{
		i++;
	}
	while(source[i]!='\0')
	{
		if(source[i]==' ') {i++;continue;}
		dest[j]=source[i];
		i++;
		j++;
	}
}
int main(int argc, char *argv[]) 
{
	system("cls");
	char cmd[128]={'\0'};
	char buf[128]={'\0'};
	char th;
	FILE* pfile;
	char cwdbuf[128]={'\0'};
	char tbbuf[128]={'\0'};
	int i=0,j=0;
	int ptr=0;
	while(1)
	{
		ptr=0;
		printf("#:");
		scanf("%c",&th);
		if(th==10)
		{
			fflush(stdin);
			continue;
		}
		else
		{
			--(stdin->_ptr);
			while(*stdin->_ptr!=10)
			{
				cmd[ptr]=*stdin->_ptr;
				ptr++;
				stdin->_ptr++;


			}
			fflush(stdin);
		}

		if(strcmp(cmd,"quit")==0) return 0;
		if(strcmp(cmd,"dir")==0)
		{
			system("dir /w");
		}
		if(strcmp(cmd,"h")==0 ||strcmp(cmd,"help")==0)
		{
			printf("系统正处于建设阶段,目前只支持以下命令:\n\n  dir          h/help      quit\n");
			printf("  getpath      setpath     create\n");
			//printf("程序所有者:wp231957\n");
		}
		if(strcmp(cmd,"getpath")==0)
		{
			_getcwd(cwdbuf,128);
			printf("当前工作路径是:%s\n",cwdbuf);
		}
		if(strstr(cmd,"setpath")!=NULL)
		{
			i=0;
			j=0;
			while(cmd[i]!=' ')
			{
				i++;
			}
			memset(cwdbuf,'\0',128);
			while(cmd[i]!='\0')
			{
				if(cmd[i]==' ') {i++;continue;}
				cwdbuf[j]=cmd[i];
				i++;
				j++;
			}
			//printf("待转换的当前工作路径是:%s\n",cwdbuf);
			if(_chdir(cwdbuf)==0)
			{
				_getcwd(cwdbuf,128);
				printf("当前工作路径是:%s\n",cwdbuf);
			}
			else   printf("重置工作路径失败");
			
		}
		if(strstr(cmd,"create")!=NULL)
			{
				//printf("能够运行到此处\n");
				memset(tbbuf,'\0',128);
				getcmd(&cmd[0],tbbuf);
				if(tbbuf[0]=='\0')
				{
					printf("此命令需要参数\n");
					continue;
				}
				else
				{
					strcat(tbbuf,".wpdb");
					//printf("文件:%s\n",tbbuf);
					if(_access(tbbuf, 0)==0) 
					{
						printf("%s文件已经存在,请重新输入。\n",tbbuf);
						memset(tbbuf,'\0',128);
						continue;
					}
					else
					{
						pfile=fopen(tbbuf,"w+");
						fseek(pfile, 8,SEEK_SET);
						fwrite("WPDB",sizeof(char),4,pfile);
						buf[0]=100;
						buf[1]='\0';
						fseek(pfile, 12,SEEK_SET);
						fwrite(buf,sizeof(char),2,pfile);
						fclose(pfile);
						printf("%s创建成功。\n",tbbuf);
					}
				}

			} 
		memset(cmd,'\0',128);
		memset(cwdbuf,'\0',128);

	}

	return 0;
}