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

fopen() สำหรับไฟล์ที่มีอยู่แล้วในโหมดเขียน (write mode) ใน C

fopen() เปิดไฟล์ที่ pointer ชี้ ไว้ read ("r") หรือ write ("w")

ถ้าไฟล์มีอยู่แล้วและเปิดในโหมด "w" จะถูกทำให้เป็นไฟล์ว่างเปล่า (override เนื้อหาเดิม)

ไวยากรณ์

FILE *fopen(const char *filename, const char *access_mode)

filename: ชื่อไฟล์, access_mode: โหมดการเข้าถึง (r, w, a, ...)

ตัวอย่าง

ไฟล์ "one.txt" มีเนื้อหา: "This is demo text! This is demo text! This is demo text!"

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

void main() {
    FILE *f;
    int len;
    f = fopen("one.txt", "r");
    if(f == NULL) {
        perror("Error opening file");
        return -1;
    }
    fseek(f, 0, SEEK_END);
    len = ftell(f);
    fclose(f);
    printf("Size of file: %d bytes", len);
    getch();
}

ผลลัพธ์

Size of file: 78 bytes

ใช้ fopen() เปิดไฟล์ fseek() ไปท้าย ftell() บอกขนาด