考慮以下幾點:基本鐺:sprintf的復位詮釋計數器爲0
int fileNo = 0;
sprintf(outfile, "%03d.jpg", fileNo);
後來
fileNo++; // fileNo equals 1 now
然後,如果你再次調用此:
sprintf(outfile, "%03d.jpg", fileNo);
fileNo
現在等於0再次。
這裏的目標是保留一個計數器在fileNo
,然後將該值傳遞給sprintf
以設置文件名。有一種更簡單的方法將計數器轉換爲字符串值嗎?或者我只是錯過了一個步驟,可能會阻止fileNo
被重置爲零?
我一直在挖掘到malloc
,但它不是很清楚什麼時候這是必要的。幫幫我?
(我沒有新的節目,但新C.)
更新
這是一個非常簡單的程序。沒有重新分配。當我進入調試器時,執行sprintf
行後,fileNo立即復位爲0。
...
static int fileNo = 0;
char outfile[7];
sprintf(outfile, "%03d.jpg", fileNo);
...
while(fread(buffer, 1, 512, inptr) == 512)
{
// 0xff 0xd8 0xff
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff)
{
if (!found1stJPG)
{
found1stJPG = true;
} else {
fileNo++;
fclose(outptr);
sprintf(outfile, "%03d.jpg", fileNo); // fileNo is 1 before this executes
printf("outfile: %s,\n", outfile); // in the debugger fileNo is now 0
}
你可能不得不展示更多的代碼,但我懷疑'fileNo'超出了範圍,然後一個新的'fileNo'被實例化爲'0'的值。如果將'int fileNo = 0;'更改爲'static int fileNo = 0;'會發生什麼? – mttrb
'sprintf'不會將計數器重置爲0.您的代碼確實如此。我們看不到的部分。 – Jens
請創建一個[最小,完整和可驗證的示例](http://stackoverflow.com/help/mcve)並向我們展示,否則我們幾乎不可能爲您提供幫助。 –