Академический Документы
Профессиональный Документы
Культура Документы
Technology
Ankit Yadav(140120119254)
vijay Yadav(140120119255)
Guided by : Prof.
Different
modes
mode
Writing
if
else
Appending
if
else
Reading
if
mode
mode
else
error occurs.
Additional
r+
modes
w+
a+
Opening a FILE
Syntax
Closing a FILE
When
Example:
FILE *p1;
p1 = fopen(INPUT.txt, r);
..
..
fclose(p1);
Input/output
operations
on FILES
C provides several different functions for reading/writing
syntax:
c
: a character variable
fp1
syntax:
c
putc(c,fp1);
c = getc(fp2);
: a character variable
fp2
file
getc()
Program to read/write
using getc() & putc()
#include
<stdio.h>
main()
{
FILE *fp1;
char c;
f1= fopen(INPUT, w); /* open file for writing */
while((c=getchar()) != EOF) /*get char from keyboard until CTL-Z*/
putc(c,f1); /*write a character to INPUT */
fclose(f1); /* close INPUT */
f1=fopen(INPUT, r); /* reopen file */
while((c=getc(f1))!=EOF) /*read character from file INPUT*/
printf(%c, c); /* print character to screen */
fclose(f1);
} /*end main */
#include <stdio.h>
main()
{ int i, sum2=0;
FILE *f2;
/* open files */
f2 = fopen("int_data.txt","w");
/* write integers to files in binary and
text format*/
for(i=10;i<15;i++) printf(f2,"%d\n",i);
fclose(f2);
f2 = fopen("int_data.txt","r");
while(fscanf(f2,"%d",&i)!=EOF)
{ sum2+=i;
printf("text file: i=%d\n",i);
} /*end while fscanf*/
printf("text sum=%d\n",sum2);
fclose(f2);
}
to scanf() and
printf()
Syntax:- fprintf()
fprintf
(fp,"string",variables);
Example:
int i = 12;
float x = 2.356;
char ch = 's';
FILE *fp;
fp=fopen(out.txt,w);
fprintf (fp, "%d %f %c", i,
x, ch);
Syntax:-
fscanf()
fscanf
(fp,"string",identifiers);
Example:
FILE *fp;
Fp=fopen(input.txt,r
);
int i;
fscanf (fp,%d",i);
fscanf() returns EOF
when end-of file reached
syntax: putw(i,fp1);
i : an integer variable
syntax: i = getw(fp2);
i : an integer variable
getw() returns
file end reached
fread()
fwrite()
Declaration:
Fseek()
Program using
fseek,ftell and frewind
#include
Void main()
FILE*fp;
int I;
clrscr();
fp=fopen(CHAR.txt,r);
for(i=1;i<=10;i++);
prinf(%c : %d \n,getc(fp),ftell(fp));
fseek(fp,ftell(fp),0);
if(i==5)
rewind(fp); }
fclose(fp); }