2012-07-04 58 views
1

下面的代碼生成基於文件名:目標目錄,電臺名稱和當前時間:生成文件名沒有空格

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 

(更復雜的要求會消除所有非法字符。從文件名)

謝謝。

UPDATE

如果這樣寫:

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時將整數指針沒有施放[默認啓用] 警告:賦值使整型指針無需投射[默認啓用]

+1

爲什麼你認爲空格字符是文件名的非法字符? – alk

回答

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

刪除空格,換行,製表符,回車等 注意,這也複製了空終止符。

1

如果您可以修改名稱可以使用這樣的事情:

char *remove_whitespace(char *str) 
{ 
    char *p; 

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

如果沒有,只是malloc的另一個字符串大小相同,複製原始串入並免費使用它之後。

+1

這應該被命名爲'replace_whitespace'並且還處理其他isspace()字符。 – Jens

+2

這可能是合理的,但值得一提的是,「a b」和「a_b」都會導致「a_b」,所以在映射後可能會發生不同的輸入衝突。另外,「只是malloc另一個字符串大小相同,將原始字符串複製到它」 - strdup()在一次調用中很好地完成。 –