8

我想从文件名中抛出最后三个字符并得到其余的?

我有这个代码:

char* remove(char* mystr) {

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

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

    return tmp;
}
4

11 回答 11

18

尝试:

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;
}

您必须自己释放返回的字符串。它只是找到.字符串中的最后一个并将其替换为空终止符。它将NULL通过返回来处理错误(传递或耗尽内存)NULL

它不适用于诸如在非文件部分中/this.path/is_bad找到之类的东西,但是您也可以通过执行of或任何路径分隔符来处理此问题,并确保其位置在该位置之前或之前。.strrchr/NULL.


此问题的更通用解决方案可能是:

#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;
}

这会产生:

[hello]
[hello]
[hello]
[hello.txt]
[/no.dot/in_path]
[/has.dot/in]
[/no]
于 2010-04-29T11:26:59.810 回答
10

使用rindex定位“.” 特点。如果字符串是可写的,你可以用字符串终止符 char ('\0') 替换它,你就完成了。

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.
于 2010-04-29T11:13:27.533 回答
6

如果您实际上只是想删除最后三个字符,因为您不知何故知道您的文件名的扩展名正好是三个字符长(并且您想保留点):

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;
}

或者让调用者提供目标缓冲区(他们必须确保足够长):

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

如果您想通用地删除文件扩展名,那就更难了,并且通常应该使用您的平台提供的任何文件名处理例程(basename在 POSIX 上,_wsplitpath_s在 Windows 上),如果您有可能处理的是路径而不是最后部分文件名:

/* 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;
}

想一想,您可能想要传递dst+1而不是传递dst给 strrchr,因为以点开头的文件名可能不应该被截断为“.”。要看它是干什么用的。

于 2010-04-29T11:23:33.450 回答
3

我会尝试以下算法:

last_dot = -1

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

if last_dot != -1:
    str[last_dot] = '\0'
于 2010-04-29T11:17:25.917 回答
1

为了让 paxdiablo 的第二个更通用的解决方案在 C++ 编译器中工作,我更改了这一行:

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

到:

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

希望这可以帮助某人。

于 2010-06-11T10:29:59.843 回答
0

只需将点替换为“0”即可。如果您知道您的扩展名总是 3 个字符长,您可以这样做:

字符文件[] = "test.png";
文件[strlen(文件) - 4] = 0;
放置(文件);

这将输出“测试”。此外,您不应返回指向局部变量的指针。编译器也会就此发出警告。

于 2010-04-29T11:20:51.600 回答
0

这应该做的工作:

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;
}
于 2010-04-29T11:21:14.493 回答
0

获取位置并将该位置复制到一个新的字符 * 中。

    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);
于 2012-02-16T19:51:14.033 回答
0

这是更改扩展名的简单方法。

....
char outputname[255]
sscanf(inputname,"%[^.]",outputname);  // foo.bar => foo
sprintf(outputname,"%s.txt",outputname) // foo.txt <= foo
....
于 2014-05-29T17:06:37.487 回答
0

具有可配置的最小文件长度和可配置的最大扩展长度。返回扩展名更改为空字符的索引,如果未找到扩展名,则返回 -1。

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;
}
于 2015-06-30T20:29:04.037 回答
0

我使用这段代码:

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';
}

它正确处理 Windows 路径约定(两者都/可以\是路径分隔符)。

于 2017-01-16T14:05:04.143 回答