使用你創建的字符串作爲snprintf()
的下一個調用的格式字符串。
int formatLength = /* some input */;
char filePrefix[FILEPREFIX_LEN]; // assigned by some input
const int FILENAME_LEN = strlen(filePrefix) + formatLength + 1; // +1 for terminating '\0'
char fileName[FILENAME_LEN];
int i;
for (i=0; i<numberOfFiles; i++) {
char temp[TEMPLATE_LEN]; // where TEMPLATE_LEN >= FILEPREFIX_LEN + 3 + number of characters in the decimal representation of formatLength
snprintf(temp, TEMPLATE_LEN, "%s%%0%dd", filePrefix, formatLength);
// error check snprintf here, in case the destination buffer was not large enough
snprintf(fileName, FILENAME_LEN, temp, i);
// error check snprintf here, in case the destination buffer was not large enough
// use fileName
}
因此,如果您filePrefix
= 「文件」,那麼你會得到fileName
= 「file0001」, 「file0002」, 「file0003」,等等...
雖然很多這樣的工作實際上不是依賴於i
,所以你可以在循環外移動它,就像這樣:
int formatLength = /* some input */;
char filePrefix[FILEPREFIX_LEN]; // assigned by some input
const int FILENAME_LEN = strlen(filePrefix) + formatLength + 1; // +1 for terminating '\0'
char fileName[FILENAME_LEN];
char temp[TEMPLATE_LEN]; // where TEMPLATE_LEN >= FILEPREFIX_LEN + 3 + number of characters in the decimal representation of formatLength
snprintf(temp, TEMPLATE_LEN, "%s%%0%dd", filePrefix, formatLength);
// error check snprintf here, in case the destination buffer was not large enough
int i;
for (i=0; i<numberOfFiles; i++) {
snprintf(fileName, FILENAME_LEN, temp, i);
// error check snprintf here, in case the destination buffer was not large enough
// use fileName
}
在這些情況下,您的temp
(簡稱「模板」,而不是「臨時」)將是「前綴%04d「(例如,前綴長度爲4,filePrefix爲 「字首」)。因此,您需要注意,您的filePrefix
不包含任何對printf
函數族具有特殊含義的字符。如果你事先知道它不會,那麼你很好。
但是,如果可能的話,那麼你需要做兩件事之一。在使用它之前,您可以通過轉義所有特殊字符來處理filePrefix
。在第一snprintf()
年初
snprintf(temp, TEMPLATE_LEN, "%%s%%0%dd", formatLength);
// other stuff...
snprintf(fileName, FILENAME_LEN, temp, filePrefix, formatLength);
注意額外%
:或者你可以改變你snprintf()
調用像這些。這使得模板模式「%s%04d」(例如,對於4的prefixLength),然後在第二次調用時添加filePrefix,以便它的內容不是第二次調用中模式字符串的一部分。
所以你需要添加前導零? – Jiminion
或者您需要從file0004中獲得值4?的atoi(* PTR + 4); – Jiminion
所以你希望你的最終結果是這樣的:當'i = 4'時,結果是'filePrefix0004';當'i = 123'時,結果是'filePrefix0123'。那是對的嗎? – wlyles