FILE HANDLING IN C LANGUAGE
We have 5 type of file handling
1. Create
2. Write
3. Read
4. Delete
5. Size
/**
* C program to create a file and write data into file.
*/
#include <stdio.h>
#include <stdlib.h>
#define DATA_SIZE 1000
int main()
{
/* Variable to store user content */
char data[DATA_SIZE];
/* File pointer to hold reference to our file */
FILE * fPtr;
/*
* Open file in w (write) mode.
* "data/file1.txt" is complete path to create file
*/
fPtr = fopen("data/file1.txt", "w");
/* fopen() return NULL if last operation was unsuccessful */
if(fPtr == NULL)
{
/* File not created hence exit */
printf("Unable to create file.\n");
exit(EXIT_FAILURE);
}
/* Input contents from user to store in file */
printf("Enter contents to store in file : \n");
fgets(data, DATA_SIZE, stdin);
/* Write data to file */
fputs(data, fPtr);
/* Close file to save file data */
fclose(fPtr);
/* Success message */
printf("File created and saved successfully. :) \n");
return 0;
}
Output
Enter contents to store in file :
Hurray!!! I learned to create file in C programming. I also learned to
write contents to file. Next, I will learn to read contents from file on
Codeforwin. Happy coding ;)
File created and saved successfully. :)
DELETE THE FILE
#include<stdio.h>
int main() {
int del = remove("textFile.txt");
if (!del)
printf("The file is Deleted successfully");
else
printf("the file is not Deleted");
return 0;
}
#include<stdio.h>
int main()
{
if (remove("abc.txt") == 0)
printf("Deleted successfully");
else
printf("Unable to delete the file");
return 0;
READ A FILE IN C
#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;
printf("Enter number of students: ");
scanf("%d", &num);
FILE *fptr;
fptr = (fopen("C:\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}
for(i = 0; i < num; ++i)
{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);
printf("Enter marks: ");
scanf("%d", &marks);
fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);
}
fclose(fptr);
return 0;
}
FILE SIZE IN C
#include<stdio.h>
#include<conio.h>
void main()
FILE *fp;
char ch;
int size = 0;
fp = fopen("MyFile.txt", "r");
if (fp == NULL)
printf("\nFile unable to open...");
else
{
printf("\nFile opened...");
fseek(fp, 0, 2); /* File pointer at the end of file */
size = ftell(fp); /* Take a position of file pointer in
size variable */
printf("The size of given file is: %d\n", size);
fclose(fp);