我正在瀏覽一些舊的C代碼(下面列出),以便在新項目中重新使用它,並且我意識到我已經放棄了最終返回語句。特殊的事情是,例程工作完美,並沒有返回正確的文件指針。任何人都可以向我解釋爲什麼這是?從C函數返回FILE指針時的奇怪行爲
FILE* openforwrite(char *name, int binary)
{
//broken out from main to keep it tidy and allow multiple output files.
FILE *file;
//first see if it exists
file = fopen(name,"r");
if (file)
{ // it does, delete it
fclose(file);
if(remove(name)) bail("Output file already exists and cannot be deleted.");
}
//now lets re-create and open it for writing
if (binary)
file = fopen(name, "wb");
else
file = fopen(name, "w");
//check it actually opened
if (!file)
bail("Error opening output file.");
//and pass the pointer back
return file; // <-- I had omitted this line initially but the routine still worked
}
您可以在文件上使用'stat()'來查看它是否存在,而不是打開/關閉。請注意,您的代碼很活潑,如果在關鍵應用程序中使用,可能會讓某些人使用計時攻擊來代替指定的文件名滑入符號鏈接,並讓您的應用程序在應該塗寫的地方塗寫數據。 –
I'米驚訝它編譯 - 似乎是一個非void返回類型的函數不返回任何不會編譯。 – jedwards
謝謝Marc,這是一個很好的觀點,下次使用時我會這樣做。 – Tyr