我有以下用C语言编写的代码,它从linux复制mv (move)命令的功能。问题是代码效率很低。如何在不过多更改结构的情况下优化代码或使代码更高效?
#include <limits.h>
#include <fcntl.h>
#include "ourhdr.h"
#include <sys/stat.h>
#include <dirent.h>
int main(int argc,char *argv[])
{
if(argc!=3)
{
printf("<Sintaxa> <fisier sursa> <fisier destinatie> \n");
exit(1);
}
int ren1,ren2;
struct stat buf1;
struct stat buf2;
lstat(argv[2],&buf1);
lstat(argv[1],&buf2);
char src[PATH_MAX];
strcpy(src,argv[1]);
char dst[PATH_MAX];
strcpy(dst,argv[2]);
int src_size = (int)strlen(src);
int dst_size = (int)strlen(dst);
dst[dst_size] = '/';
dst[dst_size + 1] = '\0';
dst_size++;
int i;
int index=0;
int index1=src_size;
while(--index1>0)
{
if(src[index1]=='/')
{
index1=0;
}
else
index++;
}
for (i = src_size-index-1; i < src_size; i++)
{
dst[dst_size++] = src[i];
}
dst[dst_size] = '\0';
if (access(src,F_OK)==-1)
{
err_ret("%s: cannot stat '%s'", argv[0],argv[1]);
return -1;
}
if(S_ISDIR(buf1.st_mode))
{
if(((S_ISDIR(buf2.st_mode))&&(!(opendir(argv[1]))))||(!(opendir(argv[2]))))
{
err_quit("%s: cannot move '%s' to '%s': Permission denied \n", argv[0],argv[1],dst);
}
ren1=rename(src,dst);
if(ren1!=0)
{
err_quit("Error: unable to move the file");
}
}
else
{
ren2=rename(argv[1],argv[2]);
if(ren2!=0)
{
err_quit("Error: unable to rename the file ");
}
}
}上面的代码运行良好,但效率很低。
发布于 2020-05-15 11:24:12
这是一个小程序,所以有些问题不大可能。如果这是API的一部分,那么问题就会层出不穷,然后产生实际的差异。
有几点你应该去做:
opendir泄漏:opendir打开一个文件描述符。您打开两个目录,其中没有一个是关闭的。一定要打电话给closedir。如果这是API的一部分,那么这些内存泄漏就会堆积起来。否则,这可能不是一个问题,因为当过程结束时,应该自动清除描述符。src的名称并将其复制到dst。您可以通过使用内置函数来改进它。使用strrchr查找最后一个/和strcpy来复制名称。也许还有其他可能的变化,但这应该是它的要点。这些问题中的大多数影响很小。这是一个小程序,所以您不会注意到必须进行性能更改(除非这是一个API)。
https://codereview.stackexchange.com/questions/242248
复制相似问题