模式下為現有檔案使用 fopen()


函式 fopen() 開啟由指標指向的檔案並讀寫該檔案。在寫模式中使用“w”,而在讀模式中使用“r”。

當某個檔案存在於目錄中時,它將被視為一個新的空檔案,並用新資料覆蓋檔案的內容。

以下是 C 語言中 fopen() 的語法:

FILE *fopen(const char *filename, const char *access_mode)

在此處,

filename − 要開啟的檔案的名稱。

acess_mode − 訪問檔案時的模式,例如讀模式或寫模式。

以下是在 C 語言中 fopen() 的示例:

假設我們有一個名為“one.txt”的檔案,其中包含以下內容。

This is demo text!
This is demo text!
This is demo text!

現在,我們來看一下該示例。

示例

#include <stdio.h>
#include<conio.h>
void main () {
   FILE *f;
   int len;
   f = fopen("one.txt", "r");
   if(f == NULL) {
      perror(“Error opening file”);
      return(-1);
   }
   fseek(f, 0, SEEK_END);
   len = ftell(f);
   fclose(f);
   printf("Size of file: %d bytes", len);
   getch();
}

輸出

Size of file: 78 bytes

在上面的程式中,聲明瞭一個檔案型別指標變數 f,並使用 fopen() 函式用它來開啟名為“one.txt”的檔案。

FILE *f;
int len;
f = fopen("one.txt", "r");

更新於: 26-6 月-2020

595 次瀏覽

開啟你的 事業

完成課程並獲得認證

開始
廣告
© . All rights reserved.