2014-06-06 58 views
0

我試圖使用sscanf()刪除文件的擴展名(我知道它是.txt)。我嘗試過很多格式的字符串,我認爲它可能會工作,但沒有成功。主要問題是我只是不明白sscanf()的文檔,所以我不知道如何使用這個[=%[*][width][modifiers]type=]我試圖告訴它,結尾必須是「.txt」或者將初始字符串保存在一個變量中和%4c對應於另一個的擴展名,但是再次...不能使其工作。sscanf獲得由兩個固定字符串包圍的字符串段

我知道這已被問在此之前:sscanf: get first and last token in a string但正如我所說......我不明白它的解決方案。

我的代碼,做了一部分:

sscanf(fileName,"the_sender_is_%s%*[.txt]", sender); 

輸入文件名,例如: 「the_sender_is_Monika.txt」

sender我應該有

Monika 

但無論我嘗試給我

Monika.txt 
+0

目前尚不清楚你的要求。也許你可以發佈一些代碼來解釋你想要做什麼以及你認爲問題出在哪裏。 –

+0

我需要保存文件的名稱(不帶擴展名)。我必須使用sscanf,多數民衆贊成 – divmermarlav

+0

你所要求的不清楚,因爲'sscanf'用於從字符串中讀取數據。這與保存文件名無關。 –

回答

1

當您使用

sscanf(fileName,"the_sender_is_%s%*[.txt]", sender); 

該功能可以讀取儘可能多的,因爲它可以與%s它處理%*[.txt]之前。

使用

sscanf(fileName,"the_sender_is_%[^.]", sender); 
+0

來自http://www.cplusplus.com/reference/cstdio/scanf/?kw=scanf:'[^ characters] \t否定掃描集\t任意數量的字符,它們都不會被指定爲括號之間的字符。 –

2

雖然sscanf()功能強大,但它不是通用工具。你可以用它做什麼是有限的,而你正在擊中它們。適度逼近任務是:

char body[32]; 
char tail[5]; 
if (sscanf("longish-name-without-dots.txt", "%31[^.]%4s", body, tail) != 2) 
    …oops — can't happen with the constant string, but maybe with a variable one… 

這讓你longish-name-without-dotsbody.txttail。但是如果在擴展之前的名稱部分有點,它將無法很好地工作。

你可能在尋找:

const char *file = "longish-name.with.dots-before.txt"; 
char *dot = strrchr(file, '.'); 
if (dot == NULL) 
    …oops — can't happen with the literal, but maybe with a variable… 
strcpy(tail, dot); // Beware buffer overflow 
memcpy(body, file, dot - file); 
body[dot - file] = '\0';