C語言中fopen()函數(shù)的使用方法示例詳解
fopen()函數(shù)的使用方法
C語言中fopen()的基本用法:
語法:
FILE *fopen(const char *filename, const char *mode);`
返回值:
fopen函數(shù)返回新打開文件的文件指針;如果此文件不能打開,則返回NULL指針。
所需頭文件:
#include <stdio.h>`
參數(shù)和模式
- filename: 要打開的文件名字符串
- mode: 訪問文件的模式, 它包括:
一個簡單的表格是這么創(chuàng)建的:
模式 | 描述 | 文件可否存在 |
---|---|---|
"r" | 打開文件僅供讀取 | 必須存在 |
"w" | 創(chuàng)建新文件僅供寫入 | 若存在,則清空后再寫入 |
"a" | 打開文件附加寫入 | 若不存在,則創(chuàng)建新文件寫入 |
"r+" | 打開文件供讀取并寫入 | 必須存在 |
"w+" | 創(chuàng)建新文件供讀取并寫入 | 若存在,則清空后再寫入 |
"a" | 打開文件讀取并附加寫入 | 若不存在,則創(chuàng)建新文件寫入 |
下段代碼展示了一個簡單的fopen函數(shù)的讀取與寫入。
#include <stdio.h> #include <stdlib.h> int main () { FILE * fp; fp = fopen ("Ifile.txt", "w+"); fprintf(fp, "%s %s %s %d", "We", "are", "in", 2020); fclose(fp); return(0); }
運行后:
We are in 2012
我們再嘗試讀取這個file:
#include <stdio.h> int main () { FILE *fp; int ch; fp = fopen("Ifile.txt","r"); while(1) { ch = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", ch); } fclose(fp); return(0); }
運行后:
We are in 2020
reference:
https://www.tutorialspoint.com/c_standard_library/c_function_fopen.htm
https://www.techonthenet.com/c_language/standard_library_functions/stdio_h/fopen.php
到此這篇關(guān)于C語言中fopen()函數(shù)的使用方法的文章就介紹到這了,更多相關(guān)C語言fopen()函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Windows平臺下配置VS Code的C++環(huán)境教程
這篇文章主要介紹了Windows平臺下配置VS Code的C++環(huán)境教程,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-12-12