Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C의 tmpfile() 함수

<시간/>

tmpfile() 함수는 C에서 바이너리 업데이트 모드로 임시 파일을 생성합니다. C 프로그램의 헤더 파일에서 초기화합니다. 임시 파일을 만들 수 없는 경우 항상 null 포인터를 반환합니다. 임시 파일은 프로그램 종료 직후 자동으로 삭제됩니다.

구문

FILE *tmpfile(void)

반환 값

파일 생성에 성공하면 함수는 생성된 임시 파일에 대한 스트림 포인터를 반환합니다. 파일을 생성할 수 없는 경우 NULL 포인터를 반환합니다.

알고리즘

Begin.
   Declare an array variable c[] to the character datatype and take a character data string.
   Initialize a integer variable i ← 0.
   Declare a newfile pointer to the FILE datatype.
   Call tmpfile() function to make newfile filepointer as temporary file.
   Call open() function to open “nfile.txt” to perform write operation using newfile file pointer.
   if (newfile == NULL) then
      print “Error in creating temporary file” .
      return 0.
   Print “Temporary file created successfully”.
   while (c[i] != '\0') do
      put all the data of c[] into the filepointer newfile.
      i++.
   Call fclose() function to close the file pointer.
   Call open() function to open “nfile.txt” to perform read operation using newfile file pointer.
   Call rewind() function to set the pointer at the beginning of the stream of the file pointer.
   while (!feof(newfile)) do
      call putchar() function to print all the data of file pointer newfile.
      Call fclose() function to close the file pointer.
End.

예시

#include <stdio.h>
int main() {
   char c[] = "Tutorials Point";
   int i = 0;
   FILE* newfile = tmpfile(); //make the file pointer as temporary file.
   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); //set the pointer at the beginning of the stream of the file pointer.
   while (!feof(newfile))
   putchar(fgetc(newfile));
   fclose(newfile); //closing the file pointer
}

출력

Temporary file created successfully
Tutorials Point