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

พิมพ์เนื้อหาไฟล์ใน C

ตัวอย่างพิมพ์เนื้อหาไฟล์ "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

ใช้ file pointer เปิดอ่านไฟล์ fgetc() อ่านทีละตัวอักษรจนกว่า EOF