Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this code remove a file extension?

Tags:

c++

c

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.

like image 617
UberJumper Avatar asked Dec 01 '22 08:12

UberJumper


1 Answers

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");
like image 175
Soraz Avatar answered Dec 03 '22 22:12

Soraz