File là tập hợp các bản ghi (hoặc nơi lưu trữ dữ liệu vĩnh viễn trên ổ cứng). Bằng các lệnh C, ta có thể truy cập file theo nhiều cách.
Các thao tác trên file
Các thao tác có thể thực hiện trên file trong C:
- Đặt tên file.
- Mở file.
- Đọc từ file.
- Ghi vào file.
- Đóng file.
Cú pháp
Mở và đặt tên file:
FILE *File pointer;
Ví dụ: FILE * fptr;
File pointer = fopen ("Tên file", "chế độ");
Ví dụ: fptr = fopen ("sample.txt", "r");
FILE *fp; fp = fopen ("sample.txt", "w");
Đọc từ file:
int fgetc( FILE * fp );// đọc một ký tự từ file
Ghi vào file:
int fputc( int c, FILE *fp );// ghi ký tự vào luồng
Sử dụng các hàm này để sao chép nội dung từ file này sang file khác.
Ví dụ
Chương trình C sao chép nội dung file:
#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); // Mở file để đọc 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); // Mở file để ghi fptr2 = fopen(filename, "w"); if (fptr2 == NULL){ printf("Cannot open file %s \n", filename); exit(0); } // Đọc nội dung từ 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; }
Kết quả
Enter the filename to open for reading file3.txt Enter the filename to open for writing file1.txt Contents copied to file1.txt