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

In nội dung file trong C

Ví dụ đọc và in toàn bộ nội dung file text trong C:

Ví dụ

Giả sử file new.txt có nội dung:

0,hell!o 1,hello! 2,gfdtrhtrhrt 3,demo
#include <stdio.h>
#include <conio.h>

void main() {
    FILE *f;
    char ch;
    clrscr();  // Xoa man hinh (chi Windows/conio)
    f = fopen("new.txt", "r");
    if (!f) { perror("Loi mo file"); return; }
    
    while ((ch = fgetc(f)) != EOF)
        printf("%c", ch);
    
    fclose(f);
    getch();  // Cho nhan phim (conio)
}

Kết quả

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

Giải thích: Mở file mode "r" (read). Dùng fgetc đọc từng ký tự cho đến EOF. In từng ký tự ra stdout. Đóng file.

Cải tiến hiện đại (cross-platform):
#include <stdio.h>
#include <stdlib.h>

int main() {
    FILE *f = fopen("new.txt", "r");
    if (!f) { perror("Loi mo file"); return 1; }
    
    int ch;
    while ((ch = fgetc(f)) != EOF)
        putchar(ch);
    
    fclose(f);
    return 0;
}
  • Bỏ conio.h, clrscr(), getch() – không chuẩn.
  • Dùng int ch cho fgetc (để so sánh EOF đúng).
  • putchar thay printf("%c") nhẹ hơn.