C 中檔案處理基礎


這裡我們將看到 C 中一些基本檔案處理操作。操作如下所示。

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

寫入檔案

檢視程式碼以瞭解如何寫入檔案

示例程式碼

#include <stdio.h>
int main() {
   FILE *fp;
   char *filename = "sample.txt";
   char *content = "Hey there! You'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. 
", filename);       return -1;    } else {       printf("%s: opened in write mode.
", filename);    }    /* Write content to file */    fprintf(fp, "%s
", content);    if( !fclose(fp) )       printf("%s: closed successfully.
", 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 
", filename);       return;    } else {       printf("%s: opened in read mode.

", filename);    }    while ((ch = fgetc(fp) )!= EOF) {       printf ("%c", ch);    }    if (!fclose(fp))       printf("
%s: closed.
", 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("
Contents of %s -

", filename);    while ((ch = fgetc(fp) )!= EOF) {       printf ("%c", ch);    }    fclose(fp);    fp = fopen(filename, "a");    /* Write content to file */    fprintf(fp, "%s
", content);    fclose(fp);    fp = fopen(filename, "r");    printf("
Contents of %s -
", 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 'append' operation is -
This text was already there in the file.
This text is appeneded later to the file, using C programming.

更新於: 2020 年 11 月 18 日

1 千次 + 檢視

開啟您的 職業生涯

完成課程即獲得認證

開始
廣告