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

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

<시간/>

C 파일 I/O − 파일 생성, 열기, 읽기, 쓰기 및 닫기

C 파일 관리

파일은 많은 양의 영구 데이터를 저장하는 데 사용할 수 있습니다. 다른 많은 언어와 마찬가지로 'C'는 다음과 같은 파일 관리 기능을 제공합니다.

  • 파일 생성
  • 파일 열기
  • 파일 읽기
  • 파일에 쓰기
  • 파일 닫기

다음은 'C'에서 사용할 수 있는 가장 중요한 파일 관리 기능입니다.

기능 목적
열다() 파일 생성 또는 기존 파일 열기
닫기() 파일 닫기
fprintf() 파일에 데이터 블록 쓰기
fscanf() 파일에서 블록 데이터 읽기
getc() 파일에서 단일 문자 읽기
putc() 파일에 단일 문자 쓰기
getw() 파일에서 정수 읽기
putw() 파일에 정수 쓰기
fseek() 파일 포인터의 위치를 ​​지정된 위치로 설정
말() 파일 포인터의 현재 위치를 반환
되감기() 파일 시작 부분에 파일 포인터 설정


Input:
sourcefile = x1.txt
targefile = x2.txt
Output: File copied successfully.

설명

이 프로그램에서는 파일을 다른 파일로 복사하고 먼저 복사할 파일을 지정합니다. 파일을 연 다음 "읽기" 모드에서 복사하려는 파일을 읽고 "쓰기" 모드에서 대상 파일을 읽습니다.

예시

#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
   char ch;// source_file[20], target_file[20];
   FILE *source, *target;
   char source_file[]="x1.txt";
   char target_file[]="x2.txt";
   source = fopen(source_file, "r");
   if (source == NULL) {
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }
   target = fopen(target_file, "w");
   if (target == NULL) {
      fclose(source);
      printf("Press any key to exit...\n");
      exit(EXIT_FAILURE);
   }
   while ((ch = fgetc(source)) != EOF)
      fputc(ch, target);
   printf("File copied successfully.\n");
   fclose(source);
   fclose(target);
   return 0;
}