linux文件管理系统

程序功能

  • 文件复制:通过 cp <source file> <target file> 命令将一个文件复制到另一个位置。
  • 文件删除:通过 rm <filename> 命令删除指定文件。
  • 文件压缩:使用 compress <filename> <compressed package name> 命令将文件压缩成指定文件。
  • 文件解压:使用 decompress <compressed package name> <target directory> 命令将压缩包解压到指定目录。
  • 退出程序:使用exit命令退出当前程序。

项目关键和遇到的问题

  1. 如何将程序中输入的字符改写成linux系统命令的格式?

经过搜索和查阅资料,我选择了c语言中的snprintf函数,它可以方便地将若干字符串插入到固定字符串中组成新的字符串,格式是snprintf(str, sizeof(str),"11111%s1111%s1111",str1,str2);

  1. 执行compress命令时出现错误

经过仔细地排查,最终才发现是我搞错了命令中原文件和压缩文件的位置,正确顺序应该是tar -czf 压缩文件名 原文件

项目代码

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
#define MAXN 105

void copy_file(char file1[],char file2[])
{
char command[MAXN]="";
snprintf(command, sizeof(command),"cp %s %s",file1,file2);
if(system(command))
printf("Error copying file\n");
else
printf("copy successfully\n");
}

void delete_file(char file1[])
{
char command[MAXN]="";
snprintf(command, sizeof(command),"rm %s",file1);
if(system(command))
printf("Error deleting file\n");
else
printf("delete successfully\n");
}

void compress_file(char file1[],char file2[])
{
char command[MAXN]="";
snprintf(command, sizeof(command),"tar -czf %s %s",file2,file1);
if(system(command))
printf("Error compressing file\n");
else
printf("compress successfully\n");
}

void decompress_file(char file1[],char file2[])
{
char command[MAXN]="";
snprintf(command, sizeof(command), "tar -xzf %s -C %s",file1,file2);
if(system(command))
printf("Error decompressing file\n");
else
printf("decompress successfully\n");
}
void print_usage()
{
printf("Please input your command:\n");
printf("1. COPY: cp <source file> <target file>\n");
printf("2. DELETE: rm <filename>\n");
printf("3. COMPRESS: compress <filename> <compressed package name>\n");
printf("4. DECOMPRESS: decompress <compressed package name> <target directory>\n");
printf("5. EXIT: exit\n");
}
int main()
{
char str[MAXN];
char file1[MAXN],file2[MAXN];
print_usage();
while(1)
{
printf("Please input your command:\n");
scanf("%s",str);
if(!strcmp(str,"cp"))
{
scanf("%s %s",file1,file2);
copy_file(file1,file2);
}
else
if(!strcmp(str,"rm"))
{
scanf("%s",file1);
delete_file(file1);
}
else
if(!strcmp(str,"compress"))
{
scanf("%s %s",file1,file2);
compress_file(file1,file2);
}
else
if(!strcmp(str,"decompress"))
{
scanf("%s %s",file1,file2);
decompress_file(file1,file2);
}
else
if(!strcmp(str,"exit"))
{
printf("program has exit\n");
break;
}
else
{
printf("Error\n");
}
}
return 0;
}