这是否code删除一个文件扩展名? [英] Does this code remove a file extension?

查看:115
本文介绍了这是否code删除一个文件扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是不是我的code;我想弄清楚到底该做什么。这是用C写的一个大的,古老的制度(实际上这是写4年前,但最有可能由80年代末的程序员写的心态)的一部分。在code的一部分:

 字符DestFile [256];
焦炭DestFile2 [256];//这部分只是为了显示一个例子
的strcpy(DestFile/foo/boo/goo.gz)的strcpy(DestFile2,DestFile);
PTR = strrchr(DestFile2,'。');
如果(PTR!= 0){
   如果((STRCMP(PTR。广州)== 0)||
        (STRCMP(PTR,.Z)== 0)){
       * PTR = 0;
       重命名(DestFile,DestFile2);
    }
}

DestFile2没有设置任何其他地方的功能。我编译code以上,并打印出DestFile显示一切都没有改变。我能想到的,这样做的唯一事情就是删除文件扩展名(* PTR = 0),但我的C知识是非常有限的...

任何想法?它看起来像每次获取文件以.gz或.Z它重命名该文件同名的时间。


解决方案

您是正确的。

在C语言中的字符串是一个字符用ASCII码code 0终止字符数组。

因此​​,首先,DestFile被复制到DestFile2

然后,进行从右侧的扫描,以找到的最右侧的发生。
这将返回一个指针,如果没有发生发现匹配,或者为null字符。

所以,现在你有(例如名称:myfile.gz)

DestFile2


  |  -  PTR
              v
  M Y F I L E。摹ž\\ 0


然后比较,如果开始PTR匹配字符串.Z或.gz的,如果是这样,设置一个PTR指向以\\ 0,有效地截断字符串字符的值。

设置为PTR \\ 0你现在有后


  

M Y F I L E \\0克ž\\ 0


记住ç认为,当我们到达一个\\ 0的字符串完成,所以最后命名有效地说道。

 重命名(myfile.gz,MYFILE);

This isn't my code; I am trying to figure out what exactly this does. This is a part of a big, ancient system written in C (actually it was written 4 years ago, but most likely written by a late 80s programmer mentality). Part of the code:

char DestFile[256];
char DestFile2[256];

//This part is just to show an example
strcpy(DestFile, "/foo/boo/goo.gz")

strcpy ( DestFile2, DestFile );
Ptr = strrchr ( DestFile2, '.' );
if ( Ptr != 0 ) {
   if ( ( strcmp ( Ptr, ".gz" ) == 0 ) ||
        ( strcmp ( Ptr, ".Z" ) == 0 ) ) {
       *Ptr = 0;
       rename ( DestFile, DestFile2 );
    }
}

DestFile2 is not set anywhere else in the function. I compiled the code above, and printing out the DestFile shows nothing has changed. The only thing i can think of that this does is removing the file extension (*Ptr=0) but my knowledge of C is very limited...

Any ideas? It looks like every time it gets a file with .gz or .z it renames the file to the same name.

解决方案

You are correct.

In C a string is an array of chars terminated by a character with ASCII code 0.

So, first, DestFile is copied to DestFile2

Then a scan from the right is performed, to find the right-most occurrence of '.' This returns a pointer to the char that matches, or null if no occurrence is found.

So now you have (example name: myfile.gz)

DestFile2

              |- Ptr
              v    
  M y f i l e . g z \0

Then it compares if the string starting at Ptr matches .Z or .gz and if so, sets the value of the char that Ptr points to to \0, effectively truncating the string.

After setting Ptr to \0 you now have

M y f i l e \0 g z \0

Remember that c thinks a string is done when we reach a \0, so the last rename effectively says

rename("myfile.gz", "myfile");

这篇关于这是否code删除一个文件扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆