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

ฟังก์ชัน tmpfile() ในภาษา C

ฟังก์ชัน tmpfile() สร้างไฟล์ชั่วคราว (temporary file) ในโหมด binary update ในภาษา C ฟังก์ชันนี้ถูกประกาศในเฮดเดอร์ไฟล์ของโปรแกรม C จะคืนค่า null pointer หากไม่สามารถสร้างไฟล์ชั่วคราวได้ ไฟล์ชั่วคราวจะถูกลบอัตโนมัติทันทีหลังจากโปรแกรมสิ้นสุดการทำงาน

ไวยากรณ์ (Syntax)

FILE *tmpfile(void)

ค่าที่คืน (Return Value)

หากสร้างไฟล์สำเร็จ ฟังก์ชันจะคืนค่า stream pointer ไปยังไฟล์ชั่วคราวที่สร้างขึ้น หากสร้างไฟล์ไม่ได้ จะคืนค่า NULL pointer

อัลกอริทึม

เริ่มต้น
  ประกาศอาร์เรย์ตัวแปร c[] ชนิด character และกำหนดสตริงข้อมูล
  เริ่มต้นตัวแปร integer i ← 0
  ประกาศ newfile pointer ชนิด FILE
  เรียก tmpfile() เพื่อทำให้ newfile เป็นไฟล์ชั่วคราว
  เรียก open() เพื่อเปิด "nfile.txt" เพื่อเขียนข้อมูลโดยใช้ newfile file pointer
  if (newfile == NULL) แล้ว
    แสดง "Error in creating temporary file"
    คืนค่า 0
  แสดง "Temporary file created successfully"
  while (c[i] != '\0') ทำ
    ใส่ข้อมูลทั้งหมดของ c[] ลงใน file pointer newfile
    i++
  เรียก fclose() เพื่อปิด file pointer
  เรียก open() เพื่อเปิด "nfile.txt" เพื่ออ่านข้อมูลโดยใช้ newfile file pointer
  เรียก rewind() เพื่อตั้ง pointer ไปที่จุดเริ่มต้นของ stream
  while (!feof(newfile)) ทำ
    เรียก putchar() เพื่อแสดงข้อมูลทั้งหมดของ file pointer newfile
  เรียก fclose() เพื่อปิด file pointer
สิ้นสุด

ตัวอย่างโค้ด

#include <stdio.h>

int main() {
    char c[] = "Tutorials Point";
    int i = 0;
    FILE* newfile = tmpfile(); // สร้างไฟล์ชั่วคราว
    newfile = fopen("nfile.txt", "w");
    if (newfile == NULL) {
        puts("Error in creating temporary file");
        return 0;
    }
    puts("Temporary file created successfully");
    while (c[i] != '\0') {
        fputc(c[i], newfile);
        i++;
    }
    fclose(newfile);
    newfile = fopen("nfile.txt", "r");
    rewind(newfile); // ตั้ง pointer ไปที่จุดเริ่มต้นของ stream
    while (!feof(newfile))
        putchar(fgetc(newfile));
    fclose(newfile); // ปิด file pointer
}

ผลลัพธ์

Temporary file created successfully
Tutorials Point