【问题标题】:Generate filename without white space in c在c中生成没有空格的文件名
【发布时间】:2012-07-04 11:30:13
【问题描述】:

下面的代码根据目标目录、电台名称和当前时间生成文件名:

static int start_recording(const gchar *destination, const char* station, const char* time)
{
    Recording* recording;
    char *filename;

    filename = g_strdup_printf(_("%s/%s_%s"), 
        destination, 
        station,
        time);

    recording = recording_start(filename);
    g_free(filename);
    if (!recording)
        return -1;

    recording->station = g_strdup(station);

    record_status_window(recording);

    run_status_window(recording);

    return 1;
}

输出示例:

/home/ubuntu/Desktop/Europa FM_07042012-111705.ogg

问题:

同一电台名称可能在标题中包含空格:

Europa FM
Paprika Radio
Radio France Internationale
    ...........................
Rock FM

我想帮助我从生成的文件名中删除空格 输出变成这样:

/home/ubuntu/Desktop/EuropaFM_07042012-111705.ogg

(更复杂的要求是从文件名中消除所有非法字符)

谢谢。

更新

如果这样写:

static int start_recording(const gchar *destination, const char* station, const char* time)
{
    Recording* recording;
    char *filename;

    char* remove_whitespace(station)
    {
        char* result = malloc(strlen(station)+1);
        char* i;
        int temp = 0;
        for( i = station; *i; ++i)
            if(*i != ' ')
            {
                result[temp] = (*i);
                ++temp;
            }
        result[temp] = '\0';
        return result;
    }

    filename = g_strdup_printf(_("%s/%s_%s"), 
        destination, 
        remove_whitespace(station),
        time);
    recording = recording_start(filename);
    g_free(filename);
    if (!recording)
        return -1;

    recording->station = g_strdup(station);
    tray_icon_items_set_sensible(FALSE);

    record_status_window(recording);

    run_status_window(recording);

    return 1;
}

收到此警告:

警告:传递 'strlen' 的参数 1 使指针从整数而不进行强制转换 [默认启用] 警告:赋值使指针从整数不进行强制转换[默认启用]

【问题讨论】:

  • 为什么您认为空格字符是文件名的非法字符?

标签: c


【解决方案1】:
void remove_spaces (uint8_t*        str_trimmed,
                    const uint8_t*  str_untrimmed)
{
  size_t length = strlen(str_untrimmed) + 1;
  size_t i;

  for(i=0; i<length; i++)
  {
    if( !isspace(str_untrimmed[i]) )
    {
      *str_trimmed = str_untrimmed[i];
      str_trimmed++;
    }
  }
}

删除空格、新行、制表符、回车等。 请注意,这也会复制空终止字符。

【讨论】:

    【解决方案2】:

    如果您可以就地修改名称,则可以使用以下内容:

    char *remove_whitespace(char *str)
    {
       char *p;
    
       for (p = str; *p; p++) {
          if (*p == ' ') {
             *p = '_';
          }
       }
    }
    

    如果没有,就 malloc 另一个相同大小的字符串,将原来的字符串复制进去,使用后释放。

    【讨论】:

    • 这应该被命名为replace_whitespace 并且还处理其他isspace() 字符。
    • 这可能是合理的,但值得一提的是,“a b”和“a_b”都会导致“a_b”,因此映射后不同的输入可能会发生冲突。另外,“只需 malloc 另一个相同大小的字符串,将原始字符串复制到其中” - strdup() 在一次调用中就可以很好地做到这一点。
    猜你喜欢
    • 2013-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 2013-01-11
    • 1970-01-01
    相关资源
    最近更新 更多