使用您创建snprintf()
的字符串作为下一次调用的格式字符串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
= "file" 那么你会得到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
(“模板”的缩写,而不是“临时”)将是“prefix%04d”(例如,prefixLength 为 4,filePrefix 为“prefix”)。因此,您需要注意您的filePrefix
不包含任何printf
对函数族具有特殊意义的字符。如果您先验地知道它不会,那么您就可以开始了。
但是,如果可能的话,那么您需要做两件事之一。您可以filePrefix
在使用前通过转义所有特殊字符来处理它。或者您可以将snprintf()
呼叫更改为以下内容:
snprintf(temp, TEMPLATE_LEN, "%%s%%0%dd", formatLength);
// other stuff...
snprintf(fileName, FILENAME_LEN, temp, filePrefix, formatLength);
%
请注意第一个开头的额外内容snprintf()
。这使得模板模式为“%s%04d”(例如,prefixLength 为 4),然后在第二次调用中添加 filePrefix,这样它的内容就不是第二次调用中模式字符串的一部分。