tags:

views:

1388

answers:

3

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.

+13  A: 

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");
Soraz
A: 

Yeah, that's what it looks like to me too. It's renaming any .gz or .Z (gzipped or Unix Compressed files) to remove the extension.

Why it would want to do that beats me. The only use I've seen for doing such things is to get around fascist email servers that don't allow compressed attachments through.

T.E.D.
A: 

Maybe the ".gz" extension was to be removed as in ".tar.gz" to make the extension simple, like for DOS or something? Actually I can't tell from looking. Then again if the compound extension was even available in the first place that might not be it.

waynecolvin