Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Lập Trình C

Các thao tác trên file trong ngôn ngữ C


Các thao tác trên file trong C bao gồm:

  • Đặ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ác chế độ mở file

Các chế độ mở file trong C:

Chế độMô tả
rMở file để đọc
wMở file để ghi
a+Mở file để thêm (append)
r+Mở file để đọc và ghi
w+Mở file để ghi và đọc
a+Mở file để thêm và đọc
rtMở file text để đọc
wtMở file text để ghi
atMở file text để thêm
r+tMở file text để đọc và ghi
w+tMở file text để ghi và đọc
a+tMở file text để thêm và đọc
rbMở file nhị phân để đọc
wbMở file nhị phân để ghi
abMở file nhị phân để thêm
r+bMở file nhị phân để đọc và ghi
w+bMở file nhị phân để ghi và đọc
a+bMở file nhị phân để thêm và đọc
  • Chế độ ghi (Write mode):
FILE *fp; fp =fopen ("sample.txt", "w");

Nếu file chưa tồn tại, tạo file mới. Nếu đã tồn tại, nội dung cũ bị xóa, ghi nội dung mới.

  • Chế độ đọc (Read mode):
FILE *fp fp =fopen ("sample.txt", "r");

Nếu file không tồn tại, fopen trả về NULL. Nếu tồn tại, đọc dữ liệu thành công.

  • Chế độ thêm (Append mode):
FILE *fp; fp =fopen ("sample.txt", "a");

Nếu file không tồn tại, tạo file mới. Nếu tồn tại, nội dung mới được thêm vào cuối nội dung cũ.

Chế độFile tồn tạiFile không tồn tại
RĐọcfp="NULL"
WNội dung hiện tạiTạo file mới
ANội dung cũ + nội dung mớiTạo file mới

Ví dụ

Chương trình C minh họa các thao tác trên file (sao chép file):

//Program for copying the contents of one file into another 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);     // 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; }

Kết quả

Enter the filename to open for reading file2.txt Enter the filename to open for writing file1.txt Contents copied to file1.txt