首頁 > 後端開發 > C++ > C 檔案處理基礎知識

C 檔案處理基礎知識

PHPz
發布: 2023-09-16 08:29:02
轉載
1420 人瀏覽過

C 文件处理基础知识

在這裡我們將看到一些在C語言中的基本檔案處理操作。以下是這些操作的清單:

  • 在檔案中寫入內容
  • 從檔案讀取內容
  • 在檔案中追加內容

#在文件中寫入內容

請參考以下程式碼以了解如何在文件中寫入內容

範例程式碼

#include <stdio.h>
int main() {
   FILE *fp;
   char *filename = "sample.txt";
   char *content = "Hey there! You&#39;ve successfully created a file with content in c programming language.";
   /* open for writing */
   fp = fopen(filename, "w");
   if( fp == NULL ) {
      printf("%s: failed to open. </p><p>", filename);
      return -1;
   } else {
      printf("%s: opened in write mode.</p><p>", filename);
   }
   /* Write content to file */
   fprintf(fp, "%s</p><p>", content);
   if( !fclose(fp) )
      printf("%s: closed successfully.</p><p>", filename);
   return 0;
}
登入後複製

輸出

sample.txt: opened in write mode.
sample.txt: closed successfully.
登入後複製

2.從檔案中讀取

查看程式碼以了解我們如何從檔案讀取 建立一個檔案(file_read.txt):

您使用C程式語言開啟了一個唯讀模式的檔案。

範例程式碼

#include <stdio.h>
int main() {
   FILE *fp;
   char *filename = "file_read.txt";
   char ch;
   /* open for writing */
   fp = fopen(filename, "r");
   if (fp == NULL) {
      printf("%s does not exists </p><p>", filename);
      return;
   } else {
      printf("%s: opened in read mode.</p><p></p><p>", filename);
   }
   while ((ch = fgetc(fp) )!= EOF) {
      printf ("%c", ch);
   }
   if (!fclose(fp))
      printf("</p><p>%s: closed.</p><p>", filename);
   return 0;
}
登入後複製

輸出

file_read.txt: opened in read mode.
You have opened a file using C programming language, in read-only mode.
file_read.txt: closed.
登入後複製

3.將內容追加到檔案中

查看程式碼以了解如何將行追加到檔案中的方法。

建立檔案(file_append.txt)

This text was already there in the file.
登入後複製

範例程式碼

#include <stdio.h>
int main() {
   FILE *fp;
   char ch;
   char *filename = "file_append.txt";
   char *content = "This text is appeneded later to the file, using C programming.";
   /* open for writing */
   fp = fopen(filename, "r");
   printf("</p><p>Contents of %s -</p><p></p><p>", filename);
   while ((ch = fgetc(fp) )!= EOF) {
      printf ("%c", ch);
   }
   fclose(fp);
   fp = fopen(filename, "a");
   /* Write content to file */
   fprintf(fp, "%s</p><p>", content);
   fclose(fp);
   fp = fopen(filename, "r");
   printf("</p><p>Contents of %s -</p><p>", filename);
   while ((ch = fgetc(fp) )!= EOF) {
      printf ("%c", ch);
   }
   fclose(fp);
   return 0;
}
登入後複製

輸出

Contents of file_append.txt -
This text was already there in the file.
Appending content to file_append.txt...
Content of file_append.txt after &#39;append&#39; operation is -
This text was already there in the file.
This text is appeneded later to the file, using C programming.
登入後複製

以上是C 檔案處理基礎知識的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板