File Handling in C || CodeTextPro - CodeTextPro | Web Tutorial | Technology

CodeTextPro.com Provides - Web design, Technology gyan, Digital marketing, Online earnings, Seo, Adsense, Technology news, Motivation and inspiration, Latest Technology Affairs, Gadgets, Blogging

Tuesday, July 16, 2019

File Handling in C || CodeTextPro

File Handling in C Programming


A file represents a sequence of bytes on the disk where a group of related data is stored. The file is created for permanent storage of data. It is a ready-made structure.

In C language, we use a structure pointer of the file type to declare a file.

FILE *fp;

C provides a number of functions that helps to perform basic file operations. Following are the functions,


file handling in c


Opening a File or Creating a File

fp= fopen( file_name, file_mode)


file handling in c



Input/Output operation on File

In the above table, we have discussed about various file I/O functions to perform reading and writing on file.
getc() and putc() are simplest functions used to read and write individual characters to a file.

#include<stdio.h>
#include<conio.h>
main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data");
while( (ch = getchar()) != '$') {
putc(ch,fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
while( (ch = getc(fp)! = EOF)
printf("%c",ch);
fclose(fp);
}


Note: This program will read the input character-wise from the user until a '$' is pressed. Then display the contents of the file in the console.

File Handling in C Programming

Reading and Writing from File using fwrite() and fread()

** C program to write all the members of an array of structures to a file using fwrite(). Read the array

from the file and display on the screen.

#include <stdio.h>
struct student
{
char name[50];
int height;
};
int main(){
struct student stud1[5], stud2[5];
FILE *fptr;
int i;
fptr = fopen("file.txt","wb");
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);
printf("Enter height: ");
scanf("%d", &stud1[i].height);
}
fwrite(stud1, sizeof(stud1), 1, fptr);
fclose(fptr);
fptr = fopen("file.txt", "rb");
fread(stud2, sizeof(stud2), 1, fptr);
for(i = 0; i < 5; ++i)
{
printf("Name: %s\nHeight: %d", stud2[i].name, stud2[i].height);
}
fclose(fptr);

}


If you want to download file handling in c pdf file clicks the link below.

File Handling in C PDF


No comments:

Post a Comment