Home > Backend Development > C++ > body text

Creating a File Copy Program in C

WBOY
Release: 2024-09-08 16:32:32
Original
496 people have browsed it

Introduction

Creating a File Copy Program in C

In this lab, we will create a C program to copy the content of one file to another file. We will read from the source file and write the contents to the destination file.

File Structure

Create a new C file named main.c. This file will contain the program logic.

Include the necessary libraries

We need to include the stdio.h library in our program to work with files.

#include <stdio.h>
Copy after login

Declare file pointers

We need to declare two file pointers, one for the source file and one for the destination file.

FILE *fp1, *fp2;
Copy after login

Open source file

We need to open the source file for reading. If the file cannot be opened, we will print an error message and exit the program.

if ((fp1 = fopen("source.txt", "r")) == NULL) {
    printf("\nFile cannot be opened.");
    return;
}
Copy after login

Open destination file

We need to create and open the destination file for writing.

fp2 = fopen("destination.txt", "w");
Copy after login

Copy file contents

We will read the source file character by character and write into the destination file until the end of the file is reached.

char ch;
while ((ch = fgetc(fp1)) != EOF) {
    fputc(ch, fp2);
}
Copy after login

Close the files

After copying the contents, we need to close both the files.

fclose(fp1);
fclose(fp2);
Copy after login

Summary

In this lab, we learned how to read contents of one file and write them to another file. We used the fopen() function to open files and fgetc() and fputc() functions to read and write file contents. It is essential to close the files after completing the task using the fclose() function.


? Practice Now: Program Copy File


Want to Learn More?

  • ? Learn the latest C Skill Trees
  • ? Read More C Tutorials
  • ? Join our Discord or tweet us @WeAreLabEx

The above is the detailed content of Creating a File Copy Program in C. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!