10

I want to throw the last three character from file name and get the rest?

I have this code:

char* remove(char* mystr) {

    char tmp[] = {0};
    unsigned int x;

    for (x = 0; x < (strlen(mystr) - 3); x++)
        tmp[x] = mystr[x];

    return tmp;
}
2
  • 6
    You know that "file extension" and "last three characters of a file name" are not the same thing? Some files have more or less than 3 characters in their extenson: Foo.java, foo.c are good examples. Some even have multiple dots in the extension(s): foo.tar.gz. And still others will have a dot outside the extension: foo.bar.txt. In short: it's a non-trivial task. Apr 29, 2010 at 11:15
  • 4
    What platform? It's not trivial to do this correctly in C, and there's nothing in the standard libraries (because filenames are a bit platform-specific). For example, a backslash is a path separator in Windows but not in *nix, so for some\path.to\file the result of "removing the extension" on Windows is some\path.to\file (because there is no extension), but on *nix is some\path (because the extension is to\file). Apr 29, 2010 at 11:16

11 Answers 11

20

Try:

char *remove(char* myStr) {
    char *retStr;
    char *lastExt;
    if (myStr == NULL) return NULL;
    if ((retStr = malloc (strlen (myStr) + 1)) == NULL) return NULL;
    strcpy (retStr, myStr);
    lastExt = strrchr (retStr, '.');
    if (lastExt != NULL)
        *lastExt = '\0';
    return retStr;
}

You'll have to free the returned string yourself. It simply finds the last . in the string and replaces it with a null terminator character. It will handle errors (passing NULL or running out of memory) by returning NULL.

It won't work with things like /this.path/is_bad since it will find the . in the non-file portion but you could handle this by also doing a strrchr of /, or whatever your path separator is, and ensuring it's position is NULL or before the . position.


A more general purpose solution to this problem could be:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// remove_ext: removes the "extension" from a file spec.
//   myStr is the string to process.
//   extSep is the extension separator.
//   pathSep is the path separator (0 means to ignore).
// Returns an allocated string identical to the original but
//   with the extension removed. It must be freed when you're
//   finished with it.
// If you pass in NULL or the new string can't be allocated,
//   it returns NULL.

char *remove_ext (char* myStr, char extSep, char pathSep) {
    char *retStr, *lastExt, *lastPath;

    // Error checks and allocate string.

    if (myStr == NULL) return NULL;
    if ((retStr = malloc (strlen (myStr) + 1)) == NULL) return NULL;

    // Make a copy and find the relevant characters.

    strcpy (retStr, myStr);
    lastExt = strrchr (retStr, extSep);
    lastPath = (pathSep == 0) ? NULL : strrchr (retStr, pathSep);

    // If it has an extension separator.

    if (lastExt != NULL) {
        // and it's to the right of the path separator.

        if (lastPath != NULL) {
            if (lastPath < lastExt) {
                // then remove it.

                *lastExt = '\0';
            }
        } else {
            // Has extension separator with no path separator.

            *lastExt = '\0';
        }
    }

    // Return the modified string.

    return retStr;
}

int main (int c, char *v[]) {
    char *s;
    printf ("[%s]\n", (s = remove_ext ("hello", '.', '/'))); free (s);
    printf ("[%s]\n", (s = remove_ext ("hello.", '.', '/'))); free (s);
    printf ("[%s]\n", (s = remove_ext ("hello.txt", '.', '/'))); free (s);
    printf ("[%s]\n", (s = remove_ext ("hello.txt.txt", '.', '/'))); free (s);
    printf ("[%s]\n", (s = remove_ext ("/no.dot/in_path", '.', '/'))); free (s);
    printf ("[%s]\n", (s = remove_ext ("/has.dot/in.path", '.', '/'))); free (s);
    printf ("[%s]\n", (s = remove_ext ("/no.dot/in_path", '.', 0))); free (s);

    return 0;
}

and this produces:

[hello]
[hello]
[hello]
[hello.txt]
[/no.dot/in_path]
[/has.dot/in]
[/no]
4
  • if i want only the file name without extension and with out the path? thanks
    – alaamh
    Apr 29, 2010 at 19:43
  • you have a memory leak in both cases, you need to free retstr. Feb 3, 2016 at 1:13
  • 2
    @WoodrowBarlow, I'm pretty certain you're mistaken, there is no memory leak in either case. In both of them, the allocated memory is passed back to the caller and it is the caller's responsibility to free the memory. In fact, the first textual paragraph states exactly that (You'll have to free the returned string yourself), and the main() in the second code block shows how, with the s memory being freed by the caller after printing it.
    – paxdiablo
    Feb 3, 2016 at 1:29
  • 1
    my apologies, i am mistaken. Feb 3, 2016 at 1:50
13

Use rindex to locate the "." character. If the string is writable, you can replace it with the string terminator char ('\0') and you're done.

char * rindex(const char *s, int c);

 DESCRIPTION
 The rindex() function locates the last character matching c (converted to a char) in the null-terminated string s.

NOTE: This will not be recognized by later versions of gcc, and, probably, other compilers. Instead, #include string.h instead of strings.h, and use strrchr.

3
  • 3
    This maps "some/path.name/readme" to "some/path", which is wrong. It might be that this input is impossible, but I think it's worth stating the assumptions. Apr 29, 2010 at 11:24
  • 2
    Additionally, you may wish to consider changing the function name. The routine remove() is generally used for removing/deleting a file from the directory.
    – Sparky
    Apr 29, 2010 at 11:29
  • 6
    It's worth noting that rindex is not ISO-C: strrchr may be a better option.
    – paxdiablo
    Apr 29, 2010 at 12:21
7

If you literally just want to remove the last three characters, because you somehow know that your filename has an extension exactly three chars long (and you want to keep the dot):

char *remove_three(const char *filename) {
    size_t len = strlen(filename);
    char *newfilename = malloc(len-2);
    if (!newfilename) /* handle error */;
    memcpy(newfilename, filename, len-3);
    newfilename[len - 3] = 0;
    return newfilename;
}

Or let the caller provide the destination buffer (which they must ensure is long enough):

char *remove_three(char *dst, const char *filename) {
    size_t len = strlen(filename);
    memcpy(dst, filename, len-3);
    dst[len - 3] = 0;
    return dst;
}

If you want to generically remove a file extension, that's harder, and should normally use whatever filename-handling routines your platform provides (basename on POSIX, _wsplitpath_s on Windows) if there's any chance that you're dealing with a path rather than just the final part of the filename:

/* warning: may modify filename. To avoid this, take a copy first
   dst may need to be longer than filename, for example currently
   "file.txt" -> "./file.txt". For this reason it would be safer to
   pass in a length with dst, and/or allow dst to be NULL in which
   case return the length required */
void remove_extn(char *dst, char *filename) {
    strcpy(dst, dirname(filename));
    size_t len = strlen(dst);

    dst[len] = '/';
    dst += len+1;

    strcpy(dst, basename(filename));
    char *dot = strrchr(dst, '.');
    /* retain the '.' To remove it do dot[0] = 0 */
    if (dot) dot[1] = 0;
}

Come to think of it, you might want to pass dst+1 rather than dst to strrchr, since a filename starting with a dot maybe shouldn't be truncated to just ".". Depends what it's for.

0
3

I would try the following algorithm:

last_dot = -1

for each char in str:
    if char = '.':
        last_dot = index(char)

if last_dot != -1:
    str[last_dot] = '\0'
1

Just replace the dot with "0". If you know that your extension is always 3 characters long you can just do:

char file[] = "test.png";
file[strlen(file) - 4] = 0;
puts(file);

This will output "test". Also, you shouldn't return a pointer to a local variable. The compiler will also warn you about this.

1

To get paxdiablo's second more general purpose solution to work in a C++ compiler I changed this line:

if ((retstr = malloc (strlen (mystr) + 1)) == NULL)

to:

if ((retstr = static_cast<char*>(malloc (strlen (mystr) + 1))) == NULL)

Hope this helps someone.

0

This should do the job:

char* remove(char* oldstr) {
   int oldlen = 0;
   while(oldstr[oldlen] != NULL){
      ++oldlen;
   }
   int newlen = oldlen - 1;
   while(newlen > 0 && mystr[newlen] != '.'){
      --newlen;
   }
   if (newlen == 0) {
      newlen = oldlen;
   }
   char* newstr = new char[newlen];
   for (int i = 0; i < newlen; ++i){
      newstr[i] = oldstr[i];
   }
   return newstr;
}
0

Get location and just copy up to that location into a new char *.

    i = 0;
    n = 0;
    while(argv[1][i] != '\0') { // get length of filename
        i++; }

    for(ii = 0; i > -1; i--) { // look for extension working backwards
        if(argv[1][i] == '.') {
            n = i; // char # of exension
            break; } }

memcpy(new_filename, argv[1], n);
0

This is simple way to change extension name.

....
char outputname[255]
sscanf(inputname,"%[^.]",outputname);  // foo.bar => foo
sprintf(outputname,"%s.txt",outputname) // foo.txt <= foo
....
1
  • 1
    This is broken for relative file-paths that start with .. and likely .
    – bazz
    Sep 2, 2015 at 15:05
0

With configurable minimum file length and configurable maximum extension length. Returns index where extension was changed to null character, or -1 if no extension was found.

int32_t strip_extension(char *in_str)
{
    static const uint8_t name_min_len = 1;
    static const uint8_t max_ext_len = 4;

    /* Check chars starting at end of string to find last '.' */
    for (ssize_t i = sizeof(in_str); i > (name_min_len + max_ext_len); i--)
    {
        if (in_str[i] == '.')
        {
            in_str[i] = '\0';
            return i;
        }
    }
    return -1;
}
0

I use this code:

void remove_extension(char* s) {
  char* dot = 0;
  while (*s) {
    if (*s == '.') dot = s;  // last dot
    else if (*s == '/' || *s == '\\') dot = 0;  // ignore dots before path separators
    s++;
  }
  if (dot) *dot = '\0';
}

It handles the Windows path convention correctly (both / and \ can be path separators).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.