C++ 中的檔案開啟模式(r 與 r+)
在程式語言中,檔案處理對於程式與記憶體的互動、訪問檔案和獲取檔案中的資料非常重要。
使用程式,您可以**從檔案讀取資料**,以及向檔案寫入資料,並執行更多功能。
這裡,我們將瞭解如何從檔案讀取資料。
在程式設計中,在執行任何操作之前,您需要開啟檔案。並且在程式語言中有多種模式可以開啟檔案。對檔案的訪問基於其開啟的模式。
這裡我們將學習兩種開啟檔案模式之間的區別以讀取檔案,它們是 r 和 r+。
兩者都用於在程式中讀取檔案。
開啟檔案的語法:
FILE *fp;
fp = fopen( “filename.fileextension” , “mode” )
用於開啟檔案的 r 模式:
用於開啟檔案的 r 模式僅以只讀方式開啟檔案。如果檔案不存在,則返回 NULL 字元。
演示檔案開啟的程式
示例
#include <stdio.h> #include <iostream> using namespace std; int main() { FILE* readFile; char ch; readFile = fopen("file.txt", "r"); while (1) { ch = fgetc(readFile); if (ch == EOF) break; cout<<ch; } fclose(readFile); }
輸出 -
Tutorials Point
用於開啟檔案的 r+ 模式
用於開啟檔案的 r+ 模式類似於 r 模式,但具有一些附加功能。它以讀寫模式開啟檔案。如果檔案不存在,使用 w+,程式將建立新檔案以對其進行操作。
演示以 r+ 模式開啟檔案的程式
示例
#include <stdio.h> #include <iostream> using namespace std; int main() { FILE* readFile; char ch; readFile = fopen("file.txt", "r+"); while (1) { ch = fgetc(readFile); if (ch == EOF) break; cout<<ch; } fclose(readFile); }
輸出 -
Tutorials Point
廣告