C Language / Files in C Language

It is used to store data. Two operations can be done on files(read and write).

File management functions in Credefined File management functions in C
1. Creation of a file
2. Opening a file
3. Reading a file
4. Writing to a file
5. Closing a file

Predefined File management functions in C Language
function purpose
fopen () Creating a file or opening an existing file
fclose () Closing a file
fprintf () Writing a block of data to a file
fscanf () Reading a block data from a file
getc () Reads a single character from a file
putc () Writes a single character to a file
getw () Reads an integer from a file
putw () Writing an integer to a file
fseek () Sets the position of a file pointer to a specified location
ftell () Returns the current position of a file pointer
rewind () Sets the file pointer at the beginning of a file

Example Programs
Program to Write data to a file Output

#include<stdio.h>
void main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("data.txt", "w");
printf("Enter data to File:");
while( (ch = getchar()) != EOF) {
putc(ch, fp);
}

fclose(fp);
}
Enter data to File:
Wisdom Materials
Program to read data from a file Output

#include<stdio.h>
Void main()
{
FILE *fp;
char ch;
clrscr();
fp = fopen("data.txt","r");
printf("Data from File:");
while( (ch = getc(fp))!= EOF)
printf("%c",ch);
// closing the file pointer
fclose(fp);
}

Data from File:
Wisdom Materials


Home     Back