In this post, we are going to learn about how to Creating a file in C, Opening and Closing a file in C programming. This means we will learn about how to create a file in C. Let’s dive deep.
Create A File:
Let’s see with an example:
#include<stdio.h> int main() { FILE *fp; fp=fopen("abcd.txt","r"); }
Explanation:
Here the above code show how we can create or open a file where we initialize *fp as the file pointer. Then we open the file using the fopen command in a reading mode which is indicated by the word r in inverted commas.
Output:
The code runs without any error and the file which is initialized as abcd.txt gets created in the destination where we have saved our program.
Join Our WhatsApp Group
Join our WhatsApp Group To know more About Programming Language tips and how to start learning any programming language.
Closing a file in C:
As we have seen to open or create a file in C, let’s see how a file is closed in C.
Syntax:
fclose(file_pointer);
let’s see how to actually use the code.
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen("abcd.txt","r");
fclose(fp);
}
Explanation:
Here in this code we open the file as we have seen in the above case and follow the same steps and then to close the file we simply add the line fclose with the file pointer as demonstrated above.
Output:
Hence the above article demonstrates how to create or open a file and to close a file in C. Hope we were able to clear your doubts.