首頁  >  文章  >  後端開發  >  在C語言中,使用fopen()函數以寫入模式開啟現有文件

在C語言中,使用fopen()函數以寫入模式開啟現有文件

王林
王林轉載
2023-08-27 22:33:101127瀏覽

在C語言中,使用fopen()函數以寫入模式開啟現有文件

C中的fopen()方法用於開啟指定的檔案。

我們舉個例子來理解問題

語法

FILE *fopen(filename, mode)

以下是使用fopen()開啟檔案的有效模式:'r'、 'w'、'a'、'r '、'w '、'a '。詳細資訊請存取C函式庫函數- fopen()

以寫入模式開啟現有檔案的fopen()

如果要開啟的檔案在目前目錄中不存在,則會建立一個新的空文件,使用寫入模式。

如果要開啟的檔案在目前目錄中存在,並且使用‘w’ / ‘w ’打開,則在寫入之前會刪除內容。

範例

程式範例,說明我們解決方案的工作原理

#include <stdio.h>
#include <stdlib.h>

int main(){

   FILE *opFile = fopen("test.txt", "w");
   if (opFile == NULL){

      puts("Couldn&#39;t open file");
      exit(0);
   }
   else{

      fputs("includehelp", opFile);
      puts("Write operation successful");
      fclose(opFile);
   }
   return 0;
}

#輸出

Write operation successful

檔案的初始內容- C程式語言

追加作業後的內容- 包括幫助 

寫入作業會執行其工作,但會刪除在執行寫入作業之前存在於檔案中的所有內容。為了解決這個問題,C程式語言已經更新為兩種不同的方法,程式設計師可以根據程式的要求使用。

  • ‘a’(追加)模式 - 這個模式將新內容追加到檔案中已寫入的內容的末端。

  • ‘wx’模式 - 如果檔案已經存在於目錄中,將會傳回NULL。

範例

使用'a'模式示範對現有文件進行寫入操作的程式

#include <stdio.h>
#include <stdlib.h>

int main(){

   FILE *opFile = fopen("test.txt", "a");
   if (opFile == NULL){

      puts("Couldn&#39;t open file");
      exit(0);
   }
   else{

      fputs("includehelp", opFile);
      puts("Write operation successful");
      fclose(opFile);
   }
   return 0;
}

輸出

Write operation successful

文件的初始內容− C程式語言

追加操作後的內容− C程式語言includehelp

範例

使用' wx' 模式在現有檔案上進行寫入操作的程式

#include <stdio.h>
#include <stdlib.h>

int main(){

   FILE *opFile = fopen("test.txt", "wx");
   if (opFile == NULL){

      puts("Couldn&#39;t open file");
      exit(0);
   }
   else{

      fputs("includehelp", opFile);
      puts("Write operation successful");
      fclose(opFile);
   }
   return 0;
}

輸出

Write operation successful

以上是在C語言中,使用fopen()函數以寫入模式開啟現有文件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除