Академический Документы
Профессиональный Документы
Культура Документы
UNIT – V
FILE PROCESSING
FILE PROCESSING
#include<stdio.h>
#include<stdlib.h>
void main()
{
char str[100];
FILE *fp;
clrscr();
fp=fopen("a.txt","r");
while(fgets(str,5,fp)!=NULL)
puts(str);
fclose(fp);
}
Return char array if successful, Else returns NULL;
Reading : int fgetc (FILE *fp)
#include<stdio.h>
w e l c o m e EOF
void main()
{
char ch; fp
FILE *fp;
clrscr();
fp=fopen("a.txt","r");
while((ch=fgetc(fp))!=EOF)
putch(ch);
fclose(fp);
getch();
}
Return same char if successful, Else returns EOF;
int fscanf(FILE *fp , char * formatstring)
#include<stdio.h>
void main()
{
char name[20];
int roll;
float avg;
FILE *fp;
clrscr();
fp=fopen("a1.txt","r");
while((fscanf(fp,"%d%s%f",&roll,name,&avg))!=EOF)
printf("\n%d\t%s\t%f",roll,name,avg);
fclose(fp);
}
Return number of items read if successful Else returns Zero
Writing: int fputs(char *str, FILE *fp)
#include<stdio.h>
void main()
{
char str[100];
FILE *fp;
clrscr();
fp=fopen("b.txt","w");
gets(str);
fputs(str,fp);
fclose(fp);
}
Return Value
If it reads n items from the file and returns n.
Else returns end of the file
size_t fwrite(void *ptr, size_t size, size_t n,
FILE *fp);
Input :Takes 4 argument
ptr is the starting address of the memory block
n no. of items
Size – space occupied by each item
Stream – from where data will be read
Return Value
If it reads n items from the file and returns n.
Else returns end of the file
void main()
#include<stdio.h> {
struct student struct student s1;
{ struct student s2;
int roll; FILE *fp;
char name[12]; clrscr();
}; fp=fopen("c.bin","wb");
scanf("%d%s",&s1.roll,s1.name);
fwrite(&s1,sizeof(s1),1,fp);
fclose(fp);
fp=fopen("c.bin","rb");
//printf("%d%s",&s2.roll,s2.name);
fread(&s2,sizeof(s2),1,fp);
printf("%d%s",s2.roll,s2.name);
fclose(fp);
}
Binary FIle