freopen 函數(shù)說(shuō)明 函數(shù)名: freopen 功 能: 實(shí)現(xiàn)數(shù)據(jù)重定向到文件中 用 法: FILE *freopen(const char *filename, const char *mode, FILE *stream); 返回值: 成功,則返回文件指針;失敗,返回NULL(可以不使用它的返回值) 7 #include <stdio.h> int main(void) { /* redirect standard output to a file */ if (freopen("OUTPUT.FIL", "w", stdout) == NULL) { fprintf(stderr, "error redirecting stdoutn"); } /* this output will go to a file */ printf("This will go into a file."); /* close the standard output stream */ fclose(stdout); return 0; }
freopen函數(shù)通過(guò)實(shí)現(xiàn)標(biāo)準(zhǔn)I/O重定向功能來(lái)訪問(wèn)文件,而fopen函數(shù)則通過(guò)文件I/O來(lái)訪問(wèn)文件。
freopen函數(shù)在算法競(jìng)賽中常被使用。在算法競(jìng)賽中,參賽者的數(shù)據(jù)一般需要多次輸入,而為避免重復(fù)輸入,使用重定向。
freopen函數(shù)在調(diào)試中非常有用:
freopen("debug\in.txt","r",stdin)的作用就是把標(biāo)準(zhǔn)輸入流stdin重定向到debug\in.txt文件中,這樣在用scanf或是用cin輸入時(shí)便不會(huì)從標(biāo)準(zhǔn)輸入流讀取數(shù)據(jù),而是從in.txt文件中獲取輸入。
只要把輸入數(shù)據(jù)事先粘貼到in.txt,調(diào)試時(shí)就方便多了。
類似的,freopen("debug\out.txt","w",stdout)的作用就是把stdout重定向到debug\out.txt文件中,這樣輸出結(jié)果需要打開(kāi)out.txt文件查看。
需要說(shuō)明的是:
1. 在freopen("debug\in.txt","r",stdin)中,將輸入文件in.txt放在文件夾debug中,文件夾debug是在VC中建立工程文件時(shí)自動(dòng)生成的調(diào)試文件夾。如果改成freopen("in.txt","r",stdin),則in.txt文件將放在所建立的工程文件夾下。in.txt文件也可以放在其他的文件夾下,所在路徑寫正確即可。
2. 可以不使用輸出重定向,仍然在控制臺(tái)查看輸出。 3. 程序調(diào)試成功后,提交到oj時(shí)不要忘記把與重定向有關(guān)的語(yǔ)句刪除。
推薦教程: 《c》