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

Giải thích hàm fgets() và fputs() trong ngôn ngữ C


File là tập hợp bản ghi hoặc vị trí trên ổ cứng lưu trữ dữ liệu vĩnh viễn.

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ở file

FILE *File_pointer;  // Ví dụ: FILE *fptr;
File_pointer = fopen("File_name", "mode");
// Ví dụ:
fptr = fopen("sample.txt", "r");
FILE *fp = fopen("sample.txt", "w");

Hàm fgets() và fputs()

fgets() - Đọc một chuỗi từ file.

Cú pháp: fgets(char *str, int n, FILE *fp);

Ví dụ: fgets(str, 30, fp);

fputs() - Ghi một chuỗi vào file.

Cú pháp: fputs(const char *str, FILE *fp);

Ví dụ: fputs(str, fp);

Giải thích hàm fgets() và fputs() trong ngôn ngữ C

Chương trình mẫu

#include <stdio.h>
int main() {
    FILE *fptr = fopen("sample.txt", "w");
    fputs("TutorialPoints\n", fptr);
    fputs("C programming\n", fptr);
    fputs("Question & Answers", fptr);
    fclose(fptr);
    
    fptr = fopen("sample.txt", "r");
    char string[30];
    while (fgets(string, 30, fptr) != NULL) {
        printf("%s", string);
    }
    fclose(fptr);
    return 0;
}

Kết quả chạy

TutorialPoints
C programming
Question & Answers