C tmpfile() Function

beginner
9 min

C tmpfile() Function

Welcome to your journey into the world of C Programming! Today, we're diving deep into the tmpfile() function, a handy tool for creating a unique, temporary file.

What is tmpfile()? 🎯

tmpfile() is a function in the C Standard Library that creates a temporary file with a unique name and returns a pointer to the newly created file. These temporary files are automatically deleted when the program terminates.

Why tmpfile()? 💡

The tmpfile() function is particularly useful in situations where you need to write temporary data during program execution, and you don't want to manually handle the creation and deletion of files.

How to Use tmpfile() 📝

Let's write a simple C program that demonstrates the usage of tmpfile().

c
#include <stdio.h> #include <stdlib.h> int main() { FILE *tmp = tmpfile(); if (tmp == NULL) { printf("Error creating temporary file.\n"); return 1; } // Write data to the temporary file fprintf(tmp, "Hello, temporary file!\n"); // Close the temporary file fclose(tmp); printf("Temporary file created and written to successfully.\n"); return 0; }

In this example, we include the necessary header files (stdio.h and stdlib.h) and create a tmpfile() in the main() function. We check if the function call was successful, write some data to the file, close it, and print a success message.

Reading from tmpfile() 💡

To read from a tmpfile(), you can use the familiar fread() and fclose() functions. Here's an example:

c
#include <stdio.h> #include <stdlib.h> int main() { FILE *tmp = tmpfile(); if (tmp == NULL) { printf("Error creating temporary file.\n"); return 1; } // Write data to the temporary file fprintf(tmp, "Hello, temporary file!\n"); // Rewind the file pointer to the beginning rewind(tmp); char buffer[40]; size_t bytesRead; // Read data from the temporary file while ((bytesRead = fread(buffer, sizeof(char), sizeof(buffer), tmp)) > 0) { printf("Read %zu bytes: %s\n", bytesRead, buffer); } // Close the temporary file fclose(tmp); printf("Temporary file read successfully.\n"); return 0; }

In this example, we write some data to the temporary file, rewind the file pointer to the beginning, and read the data using fread(). We print the number of bytes read and the content.

Quiz 💡

Quick Quiz
Question 1 of 1

What does the `tmpfile()` function do in C programming?

Happy Coding! 🔧💻🎓