C語言程式:將一個檔案的內容複製到另一個檔案


檔案是記錄的集合(或)是硬碟上永久儲存資料的地方。 使用C命令,我們可以透過不同的方式訪問檔案。

檔案操作

在C語言中,可以對檔案執行的操作如下:

  • 命名檔案。
  • 開啟檔案。
  • 從檔案中讀取。
  • 寫入檔案。
  • 關閉檔案。

語法

**開啟和命名檔案**的語法如下:

FILE *File pointer;

例如,FILE * fptr;

File pointer = fopen ("File name”, "mode”);

例如,fptr = fopen ("sample.txt”, "r”);

FILE *fp;
fp = fopen ("sample.txt”, "w”);

**從檔案中讀取**的語法如下:

int fgetc( FILE * fp );// read a single character from a file

**寫入檔案**的語法如下:

int fputc( int c, FILE *fp ); // write individual characters to a stream

藉助這些函式,我們可以將一個檔案的內容複製到另一個檔案。

示例

以下是將一個檔案的內容複製到另一個檔案的C程式:

 線上演示

#include <stdio.h>
#include <stdlib.h> // For exit()
int main(){
   FILE *fptr1, *fptr2;
   char filename[100], c;
   printf("Enter the filename to open for reading 
");    scanf("%s",filename);    // Open one file for reading    fptr1 = fopen(filename, "r");    if (fptr1 == NULL){       printf("Cannot open file %s
", filename);       exit(0);    }    printf("Enter the filename to open for writing
");    scanf("%s", filename);    // Open another file for writing    fptr2 = fopen(filename, "w");    if (fptr2 == NULL){       printf("Cannot open file %s
", filename);       exit(0);    }    // Read contents from file    c = fgetc(fptr1);    while (c != EOF){       fputc(c, fptr2);       c = fgetc(fptr1);    }    printf("
Contents copied to %s", filename);    fclose(fptr1);    fclose(fptr2);    return 0; }

輸出

執行上述程式後,將產生以下結果:

Enter the filename to open for reading
file3.txt
Enter the filename to open for writing
file1.txt
Contents copied to file1.txt

更新於:2021年3月11日

19K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.