files
files
21
FILES
1
Senior Secondary Course
Learner’s Guide: Computer Science (330)
string line;
fout.open("sample.txt"); OPENING A FILE USING OPEN() :
o First a stream object is assigned to and
// Execute a loop If file successfully then it is used to open the file in turn.
opened SYNTAX:
while (fout) { filestream_class stream_object;
stream_object . open (“filename”);
// Read a Line from standard input
getline(cin, line); For example :
ofstream outfile;
// Press -1 to exit outfile . open (“ABC”);
if (line == "-1") outfile . close ( );
break; outfile . open (“XYZ”);
outfile.close ( )
// Write line in file
fout << line << endl; o The open () function has two parameters :
} SYNTAX:
stream_object . open (“filename”, access
// Close the File mode);
fout.close();
ios : : in for ifstream functions
// Creation of ifstream class object to read ios : : out for ofstream functions
the file
ifstream fin;
WRITE() & READ() FUNCTION :
fin.open("sample.txt"); The functions write ( ) and read ( ) have two
parameters: address of the variable, size of the
// Execute a loop until EOF (End of File) variable.
while (fin) { SYNTAX:
infile . read ( (char*) & v, sizeof v);
// Read a Line from File outfile . write ( (char*) & v, sizeof v); where v
getline(fin, line); is the variable.
2
Senior Secondary Course
Learner’s Guide: Computer Science (330)
3
Senior Secondary Course
Learner’s Guide: Computer Science (330)
ANSWERS
4. What is the return type open()
method?
A) int Answers to Check Yourself:
B) char
C) bool 1. C
D) floatis a pointer to a string 2. B
5. Which operator is used to insert the 3. A
data into file? 4. C
5. B
A) >>
B)<<
C) <
D) None of the above
STRETCH YOURSELF