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

โปรแกรม C อ่านข้อมูลจากไฟล์แสดงแบบตาราง (Tabular)


โจทย์

อ่านข้อมูลจากไฟล์ แล้วแสดงผลในรูปแบบคอลัมน์/ตาราง โดยใช้ comma (,) เป็นตัวคั่น

โหมดเปิดไฟล์

  • Write "w": สร้างใหม่/ทับเก่า
  • Read "r": อ่าน (NULL ถ้าไม่มีไฟล์)

ตรรกะการแสดงแบบตาราง

while ((ch = getc(fp)) != EOF) {
    if (ch == ',') printf("\t\t");  // comma -> tab
    else printf("%c", ch);
}

โปรแกรมตัวอย่าง

#include <stdio.h>
#include <stdlib.h>

int main() {
    char ch;
    FILE *fp;
    
    // เขียนไฟล์ทดสอบ
    fp = fopen("std1.txt", "w");
    printf("Enter data (Ctrl+Z to end):\n");
    while((ch = getchar()) != EOF) putc(ch, fp);
    fclose(fp);
    
    // อ่านและแสดงแบบตาราง
    fp = fopen("std1.txt", "r");
    printf("\nTabular output:\n");
    while((ch = getc(fp)) != EOF) {
        if(ch == ',') printf("\t\t");
        else printf("%c", ch);
    }
    fclose(fp);
    return 0;
}

ผลลัพธ์

enter the text.press cntrl Z:
Name,Item,Price
Bhanu,1,23.4
Priya,2,45.6
^Z
text on the file:
Name        Item        Price
Bhanu       1           23.4
Priya       2           45.6