Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

fgetc() และ fputc() ใน C

fgetc()

อ่านตัวอักษรจากไฟล์ คืนค่าตัวอักษร ถ้าสำเร็จ มิฉะนั้น EOF

ไวยากรณ์: int fgetc(FILE *stream)

ตัวอย่าง fgetc()

ไฟล์ "new.txt": "0,hell!o 1,hello! 2,gfdtrhtrhrt 3,demo"

#include <stdio.h>
#include <conio.h>
void main() {
    FILE *f;
    char s;
    clrscr();
    f = fopen("new.txt", "r");
    while((s = fgetc(f)) != EOF) {
        printf("%c", s);
    }
    fclose(f);
    getch();
}

ผลลัพธ์

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

fputc()

เขียนตัวอักษรลงไฟล์ คืนค่าตัวอักษร ถ้าสำเร็จ มิฉะนั้น EOF

ไวยากรณ์: int fputc(int character, FILE *stream)

ตัวอย่าง fputc()

#include <stdio.h>
void main() {
    FILE *f;
    f = fopen("new.txt", "w");
    fputc('a', f);
    fclose(f);
}

โปรแกรมจะแก้ไข "new.txt" ให้เหลือแค่ "A" (ไม่แสดงผลบนหน้าจอ)