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

Hàm fgetc() và fputc() trong C

fgetc() – Đọc ký tự từ file

Đọc 1 ký tự từ stream. Trả về int (ký tự) hoặc EOF.

int fgetc(FILE *stream);

Ví dụ đọc file

#include <stdio.h>
#include <conio.h>

void main() {
    FILE *f;
    char ch;
    clrscr();
    f = fopen("new.txt", "r");
    while ((ch = fgetc(f)) != EOF)
        printf("%c", ch);
    fclose(f);
    getch();
}

File new.txt: 0,hell!o 1,hello! 2,gfdtrhtrhrt 3,demo

Kết quả

0,hell!o 1,hello! 2,gfdtrhtrhrt 3,demo

fputc() – Ghi ký tự vào file

Ghi 1 ký tự vào stream. Trả về ký tự đã ghi, hoặc EOF nếu lỗi.

int fputc(int c, FILE *stream);

Ví dụ ghi file

#include <stdio.h>

int main() {
    FILE *f = fopen("new.txt", "w");
    if (!f) return 1;
    fputc('A', f);
    fclose(f);
    return 0;
}

File new.txt sau chạy: chỉ chứa A (ghi đè toàn bộ do mode "w").

So sánh

HàmChức năngTrả vềStream
fgetcĐọc 1 ký tựint (ký tự/EOF)FILE* (input)
fputcGhi 1 ký tựint (ký tự/EOF)FILE* (output)
getcĐọc 1 ký tự (macro)intFILE*
putcGhi 1 ký tự (macro)intFILE*
getcharĐọc từ stdinintstdin
putcharGhi ra stdoutintstdout
Lưu ý: Luôn dùng int cho biến nhận fgetc/getc để so sánh EOF đúng. fputc nhận int nhưng chỉ ghi byte thấp.