C Programming
In this tutorial we will learn to create files in C programming language.
So far we have been using the printf() and scanf() functions to print data in the console and take user input from the console respectively. And the data we were working with were all temporary and lasted till our program executed.
printf()
scanf()
Now we will learn to work with files by using I/O (Input/Output) library functions in C programming langauge.
To work with files in C programming language we have to declare them as type FILE which is defined in the standard library of I/O functions.
Syntax:
FILE *fptr;
We use the fopen() function to create a new file and use an existing file.
fopen()
FILE *fptr; fptr = fopen("filename", "mode");
Where fptr is the file pointer. "filename" is the name of the file that we want to create or use.
fptr
"filename"
filename can be like example or with extension like sample.txt or full path /path/to/file.ext.
filename
example
sample.txt
/path/to/file.ext
"mode" is how we are intending to use the file. And it takes the following values.
"mode"
r
w
a
We can also use the following in new compilers.
r+
w+
a+
Please Note!
On success the fopen() function returns a FILE pointer. Otherwise, NULL is returned.
It is important to close the file connection after use and for this we use the fclose() function.
fclose()
Syntax.
fclose(file_pointer);
Where, file_pointer is the file pointer created for the file.
file_pointer
For this we will first create a variable to hold the path of the file. Then using the fopen() function we will create the file. And then we will close the connection using the fclose() function.
#include <stdio.h> int main(void) { // creating a FILE variable FILE *fptr; // creating a variable to store filename char filename[255]; // get file path from the user printf("Enter the filename: "); scanf("%s", filename); // open the file in write mode fptr = fopen(filename, "w"); if (fptr != NULL) { printf("File created successfully!\n"); // close the file fclose(fptr); } else { printf("Failed to create the file.\n"); } return 0; }
Output:
Enter the filename: /Users/yusufshakeel/Desktop/sample/helloworld.txt File created successfully!
For this example I am entering the complete path of the file. We can also enter just the filename like helloworld.txt and it will create the file in the directory where our executable C program file resides.
helloworld.txt
Folder content before:
YUSUF-MBP:sample yusufshakeel$ pwd /Users/yusufshakeel/Desktop/sample YUSUF-MBP:sample yusufshakeel$ ls -la total 0 drwxr-xr-x 2 yusufshakeel staff 64 Jan 01 16:34 . drwx------+ 10 yusufshakeel staff 320 Jan 01 16:34 ..
Folder content after:
YUSUF-MBP:sample yusufshakeel$ ls -la total 0 drwxr-xr-x 3 yusufshakeel staff 96 Jan 01 16:37 . drwx------+ 10 yusufshakeel staff 320 Jan 01 16:34 .. -rw-r--r-- 1 yusufshakeel staff 0 Jan 01 16:37 helloworld.txt