Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

โปรแกรม C คัดลอกไฟล์ (File I/O)

คัดลอกเนื้อหาไฟล์ต้นทางไปยังไฟล์ปลายทางด้วยฟังก์ชันมาตรฐาน fgetc/fputc

ฟังก์ชัน File I/O หลัก

ฟังก์ชันหน้าที่
fopen()เปิด/สร้างไฟล์
fclose()ปิดไฟล์
fgetc()อ่านตัวอักษรเดี่ยว
fputc()เขียนตัวอักษรเดี่ยว
fprintf()/fscanf()อ่าน/เขียน formatted data
fseek()/ftell()/rewind()จัดการ file pointer

โค้ดตัวอย่าง

#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *src = fopen("x1.txt", "r");
    if (!src) { perror("open source"); exit(1); }
    FILE *dst = fopen("x2.txt", "w");
    if (!dst) { fclose(src); perror("open target"); exit(1); }

    int ch;
    while ((ch = fgetc(src)) != EOF) fputc(ch, dst);

    printf("File copied successfully.\n");
    fclose(src); fclose(dst);
    return 0;
}