Computer >> 컴퓨터 >  >> 프로그램 작성 >> C 프로그래밍

C 한 파일의 내용을 다른 파일로 복사하는 프로그램

<시간/>

파일은 기록의 모음(또는) 데이터가 영구적으로 저장되는 하드 디스크의 한 장소입니다. C 명령을 사용하여 다양한 방법으로 파일에 액세스할 수 있습니다.

파일 작업

C 언어의 파일에 대해 수행할 수 있는 작업은 다음과 같습니다. -

  • 파일 이름 지정.
  • 파일 열기.
  • 파일에서 읽기.
  • 파일에 쓰기.
  • 파일을 닫습니다.

구문

파일 열기 및 이름 지정 구문 다음과 같습니다 -

FILE *File pointer;

예:파일 * 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 \n");
   scanf("%s",filename);
   // Open one file for reading
   fptr1 = fopen(filename, "r");
   if (fptr1 == NULL){
      printf("Cannot open file %s \n", filename);
      exit(0);
   }
   printf("Enter the filename to open for writing \n");
   scanf("%s", filename);
   // Open another file for writing
   fptr2 = fopen(filename, "w");
   if (fptr2 == NULL){
      printf("Cannot open file %s \n", filename);
      exit(0);
   }
   // Read contents from file
   c = fgetc(fptr1);
   while (c != EOF){
      fputc(c, fptr2);
      c = fgetc(fptr1);
   }
   printf("\nContents 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