增加2~3个文件操作命令,并加以实现。(如移动读写指针,改变文件属性,更换文件名,改变文件保护级别)
代码:
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
string name,content;
string judge;
string fname,newname;
string file;
int main()
{
cout << "1. write (append or write)"<<endl;
cout << "2. rename (rename files)" << endl;
cout << "3. list (list files)" << endl;
cout << "4. chmod (change mode of files)" << endl;
cout << "5. exit (exit)"<<endl;
cout << "Enter order:";
int cmd;
while(cin >> cmd)
{
if(cmd == 1)
{
cout << "Input the name of the file(*.txt):";
cin >> name;
FILE *fp;
cout << "Choose the mood(w or w+):";
cin >> judge;
if(judge == "w")
{
if((fp=fopen(name.c_str(),"w"))!= NULL)
puts("open successfully");
else
{
puts("Fail to open");
break;
}
}
else if(judge == "w+")
{
if((fp=fopen(name.c_str(),"w+"))!=NULL)
puts("open successfully");
else
{
puts("Fail to open");
break;
}
}
else
{
cout << "Don't exist" << endl;
}
cout << "Enter the content:";
cin >> content;
fputs(content.c_str(),fp);
fclose(fp);
}
else if(cmd == 2)
{
cout << "Enter the old name:" << endl;
cin >> fname;
cout << "New name:";
cin >> newname;
int result;
result = rename(fname.c_str(),newname.c_str());
if(result == 0)
{
puts("Rename Successfully!");
}
else
{
puts("Fail to rename");
}
}
else if(cmd == 3)
{
cout << "enter file name or all files(*):";
cin >> fname;
if(fname == "*")
{
system("attrib *");
}
else
{
string tmp = "attrib " + fname;
system(tmp.c_str());
}
}
else if(cmd == 4)
{
long file;
struct _finddata_t find;
if((file=_findfirst("*.*",&find))==-1L)
{
printf("NULL\n");
exit(0);
}
printf("%s\n",find.name);
while(_findnext(file,&find) == 0)
{
printf("%10s\t%5d\t%d\n",find.name,find.size,find.attrib);
}
_findclose(file);
}
else if(cmd == 5)
{
break;
}
cout << "Enter your order:";
}
return 0;
}