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

Tại sao cần file trong lập trình C?


File là tập hợp bản ghi (hoặc nơi lưu trữ dữ liệu vĩnh viễn trên ổ cứng). Bằng lệnh C, ta truy cập file theo nhiều cách.

Tại sao cần file trong C

  • Toàn bộ dữ liệu mất khi chương trình kết thúc; lưu vào file giúp bảo toàn dữ liệu.

  • Nhập lượng lớn dữ liệu thủ công tốn nhiều thời gian.

  • Nếu có file dữ liệu sẵn, dễ dàng truy xuất nội dung bằng vài lệnh C.

  • Dễ dàng chuyển dữ liệu giữa các máy tính mà không thay đổi.

Các thao tác trên file

  • Đặ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

Ví dụ

Chương trình C minh họa thao tác file (ghi/đọc thông tin nhân viên):

#include<stdio.h> void main(){     //Khai báo File//     FILE *femp;     char empname[50];     int empnum;     float empsal;     char temp;     //Mở File và ghi//     femp=fopen("Employee Details.txt","w");     //Ghi dữ liệu người dùng nhập//     printf("Enter the name of employee : ");     gets(empname);     //scanf("%c",&temp);     printf("Enter the number of employee : ");     scanf("%d",&empnum);     printf("Enter the salary of employee : ");     scanf("%f",&empsal);     //Ghi vào file//     fprintf(femp,"%s\n",empname);     fprintf(femp,"%d\n",empnum);     fprintf(femp,"%f\n",empsal);     //Đóng file//     fclose(femp);     //Mở File và đọc//     femp=fopen("Employee Details.txt","r");     //Đọc từ file//     fscanf(femp,"%s",empname);     //fscanf(femp,"%d",&empnum);     //fscanf(femp,"%f",&empsal);     //In kết quả//     printf("employee name is : %s\n",empname);     printf("employee number is : %d\n",empnum);     printf("employee salary is : %f\n",empsal);     //Đóng File//     fclose(femp); }

Kết quả

Enter the name of employee : Pinky Enter the number of employee : 20 Enter the salary of employee : 5000 employee name is : Pinky employee number is : 20 employee salary is : 5000.000000