write a program to create a file in c?
Answers
Explanation:
write and append data to file. To perform any operation on file we use a built-in FILE structure. You need to create pointer to FILE type. The pointer to FILE type will hold a logical reference to our physically existed file on disk (hard disk).
In this post I will only explain how to create a file and write data into file. Step by step descriptive logic to create a file and write data into file.
Declare a FILE type pointer variable to store reference of file, say FILE * fPtr = NULL;.
Create or open file using fopen() function. fopen() function is used to open a file in different mode. You can open a file in basic three different mode r(read), w(write) and a(append) mode. We will use w file mode to create a file.
fopen("file-name", "read-mode"); function accepts two parameter first file name to read/create/write/append data, next is file open mode. On success it return pointer to FILE type otherwise NULL pointer.
Input data from user to write into file, store it to some variable say data.
C provides several functions to perform IO operation on file. For this post to make things simple I will use fputs() function to write data to file. fputs("content-to-write", stream) function accepts two parameters. First string data to write into file, next pointer to FILE type that specifies where to write data.
Use fputs() function to write data to fPtr i.e. perform fputs(data, fPtr);.
Finally after completing all operations you must close file, to save data written on file. Use fclose(fPtr) function to close file.