Professional Documents
Culture Documents
Chap14 (ICS12)
Chap14 (ICS12)
12
Types of Stream
Text stream
Binary Stream
• A sequence of bytes
• Translation is not performed in binary stream
Binary Stream • It exists with a one to one correspondence to the external devices
• It means that the number of bytes written or read is the same as the
number of bytes on the external device
Less efficient than binary stream More efficient than text stream
Example
While( ( ch==fgetc(in) ) !=EOF)
Printf(“%c”, ch);
The above loop will continues to execute until it finds the EOF character
Example
Use of newline and EoF marker
If a program gets input from a file , it will get the same data each time for execution
Syntax
FILE *MyFile;
The identifier MyFile is a file pointer
FILE is the type of MyFile pointer
The symbol '*' indicates that it is a pointer to a file structure
Syntax
File_Pointer = fopen(File_Name, Mode);
File_Pointer It is the name of file pointer declared in the program
File_Name It is name of data file to be opened. It can be string variable or string constant
If the specified file does not exist, it is created and opened
Mode It indicates the mode in which the file is to be opened
FILE MyFile;
• The above condition becomes true if there is any error during opening the file
Example
void main()
{ FILE *out;
char ch;
clrscr();
out = fopen("c:\\test.txt", "w");
printf("Enter a character (. to end): ");
ch = getche();
while(ch != '.')
{ fputc(ch, out);
ch = getche(); }
fclose(out); }
Example
void main()
{ FILE *in;
char ch;
clrscr();
if((in = fopen("c:\\test.txt", "r"))==NULL)
printf("File opening error.");
while((ch = fgetc(in)) != EOF)
printf("%c",ch);
fclose(in);
getch(); }
P a k i s t a n \0
File_Pointer It is a file pointer associated with a data file in which the string will be written
Write a program that inputs three strings from user and appends them in existing file.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
void main()
{
FILE *out;
char ch[25];
int i;
if((out = fopen("c:\\stest.txt", "a")) == NULL)
printf("File opening error.");
for(i=0; i<3; i++)
{
printf("Enter string: ");
gets(ch);
fputs(ch, out);
fputs("\n", out);
}
fclose(out);
getch();
}
File_Pointer It is a file pointer associated with data file in which formatted data will be written
Control_String It is the string that contains format specifiers and escape sequences
It indicates the format according to which data is written to data file
Write_List It is a list of variables, constants or expressions whose values are written in the file
Each item in the list is separated by comma
File_Pointer It is a file pointer associated with data file from which formatted data will be read
Control_String It is the string that contains format specifiers and escape sequences
It indicates the format according to which data is read from data file
Write_List It is a list of variables in which values are stored from the file
Each item in the list is separated by comma