2. C++ provides the following classes to perform
output and input of characters to/from files:
• ofstream: Stream class to write on files
• ifstream: Stream class to read from files
• fstream: Stream class to both read and
write from/to files.
• These classes are derived directly or
indirectly from the classes istream, and
ostream.
3. Baca Tulis File
Untuk dapat membaca atau menulis data dari/ke sebuah file maka
langkah yang perlu dilakukan adalah:
1. membuka file
- mendefinisikan variabel stream
- melakukan perintah open()
2. Melakukan pembacaan atau penulisan data
- menggunakan operand << atau >>
- menggunakan operand read() atau write()
perintah read() atau write() -> informasi ukuran data
yang akan dibaca atau ditulis sangat penting
3. Menutup file
- menggunakan perintah close()
4. This code creates a file called example.txt and inserts a sentence into it in the same
way we are used to do with cout, but using the file stream myfile instead.
5. to open a file with a stream object we use its member function open():
open (filename, mode);
Where filename is a null-terminated character sequence of type const char * (the same type that
string literals have) representing the name of the file to be opened, and mode is an optional
parameter with a combination of the following flags:
All these flags can be combined using the bitwise operator OR (|). For example, if we want to
open the file example.bin in binary mode to add data we could do it by the following call to
member function open():
Each one of the open() member functions of the classes ofstream, ifstream and fstream has a
default mode that is used if the file is opened without a second argument:
6. • For ifstream and ofstream classes, ios::in and ios::out are automatically and
respectively assumed, even if a mode that does not include them is passed
as second argument to the open() member function.
The default value is only applied if the function is called without specifying
any value for the mode parameter. If the function is called with any value in
that parameter the default mode is overridden, not combined.
File streams opened in binary mode perform input and output operations
independently of any format considerations. Non-binary files are known as
text files, and some translations may occur due to formatting of some
special characters (like newline and carriage return characters).
Since the first task that is performed on a file stream object is generally to
open a file, these three classes include a constructor that automatically calls
the open() member function and has the exact same parameters as this
member. Therefore, we could also have declared the previous myfile object
and conducted the same opening operation in our previous example by
writing:
ofstream myfile ("example.bin", ios::out | ios::app | ios::binary);
7. • Combining object construction and stream opening in a
single statement. Both forms to open a file are valid and
equivalent.
To check if a file stream was successful opening a file,
you can do it by calling to member is_open() with no
arguments. This member function returns a bool value of
true in the case that indeed the stream object is
associated with an open file, or false otherwise:
if (myfile.is_open()) { /* ok, proceed with output */ }
8. Closing a file
• When we are finished with our input and output operations on a file
we shall close it so that its resources become available again.
• We have to call the stream's member function close(). This member
function takes no parameters, and what it does is to flush the
associated buffers and close the file:
myfile.close();
Once this member function is called, the stream object can be used
to open another file, and the file is available again to be opened by
other processes.
In case that an object is destructed while still associated with an
open file, the destructor automatically calls the member function
close().
9. Text files
• Text file streams are those where we do not include the
ios::binary flag in their opening mode.
• These files are designed to store text and thus all values
that we input or output from/to them can suffer some
formatting transformations, which do not necessarily
correspond to their literal binary value.
Data output operations on text files are performed in the
same way we operated with cout:
10.
11. Data input from a file can also be performed in the same way that we did with cin:
This last example reads a text file and prints out its content on the screen. Notice
how we have used a new member function, called eof() that returns true in the case
that the end of the file has been reached. We have created a while loop that finishes
when indeed myfile.eof() becomes true (i.e., the end of the file has been reached).
12. Checking state flags
• In addition to eof(), which checks if the end of file has been reached, other member
functions exist to check the state of a stream (all of them return a bool value):
• bad()
– Returns true if a reading or writing operation fails. For example in the case that we try to write
to a file that is not open for writing or if the device where we try to write has no space left.
• fail()
– Returns true in the same cases as bad(), but also in the case that a format error happens,
like when an alphabetical character is extracted when we are trying to read an integer
number.
• eof()
– Returns true if a file open for reading has reached the end.
• good()
– It is the most generic state flag: it returns false in the same cases in which calling any of the
previous functions would return true.
•
In order to reset the state flags checked by any of these member functions we have
just seen we can use the member function clear(), which takes no parameters.
13. get and put stream pointers
• All i/o streams objects have, at least, one internal stream pointer:
ifstream, like istream, has a pointer known as the get pointer that
points to the element to be read in the next input operation.
ofstream, like ostream, has a pointer known as the put pointer that
points to the location where the next element has to be written.
Finally, fstream, inherits both, the get and the put pointers, from
iostream (which is itself derived from both istream and ostream).
These internal stream pointers that point to the reading or writing
locations within a stream can be manipulated using the following
member functions:
14. Baca Tulis File
Contoh program membuka
dan menutup file:
#include <iostream>
#include <fstream>
using namespace std;
void main() {
// Mendeklarasikan stream untuk proses input
ifstream VarBaca;
// membuka file
VarBaca.open("COBA.TXT");
// Menutup file
VarBaca.close();
}
15. Baca Tulis File
Melakukan penulisan data ke dalam file
- menggunakan operand <<
Contoh program menulis
data ke file:
Data file yang bernama #include <iostream>
“COBA.TXT” akan disimpan pada #include <fstream>
folder di mana folder tempat using namespace std;
program file berada. Atau informasi void main() {
drive dan folder harus diinputkan,
contoh: // Mendeklarasikan stream untuk proses output
“C://DATA//COBA.TXT” ofstream VarTulis;
Jika file “Coba.txt” kita buka // membuka file
dengan editor notepad, akan VarTulis.open("COBA.TXT");
tampak seperti:
VarTulis << “C++ mudah Sekali” << endl;;
VarTulis << “Pemrograman Mudah “ << endl;
// Menutup file
VarTulis.close();
}
16. Baca Tulis File
Melakukan pembacaan data dari file
- menggunakan operand >>
Contoh program membaca #include <iostream>
#include <fstream>
data dari file: using namespace std;
Data file yang bernama
void main() {
“COBA.TXT” harus sudah
ada di folder tempat program file
// Mendeklarasikan stream untuk proses output
berada. Jika tidak maka informasi
ifstream VarBaca;
drive dan folder harus diinputkan,
char Teks[80];
contoh:
“C://DATA//COBA.TXT”
// membuka file
VarBaca >> Teks; menghasilkan VarBaca.open("COBA.TXT");
satu string/kata dibaca dari file. VarBaca >> Teks; // proses membaca data dr file (1 string/kata)
Jika coba.txt hasil dari program slide cout << Teks << “ “; // “ “ -> memisahkan dg teks berikutnya
sebelumnya adalah sebagai input VarBaca >> Teks; // proses baca data dr file (1 string/kata)
file maka hasil dilayar adalah: cout << Teks;
// Menutup file
VarBaca.close();
}
17. Baca Tulis File
Melakukan pembacaan data dari file
- menggunakan operand >> dan while()
Contoh program membaca
data dari file:
#include <iostream>
Data file yang bernama #include <fstream>
“COBA.TXT” harus sudah using namespace std;
ada di folder tempat program file
berada. Jika tidak maka informasi void main() {
// Mendeklarasikan stream untuk proses output
drive dan folder harus diinputkan,
ifstream VarBaca;
contoh:
char Teks[80];
“C://DATA//COBA.TXT”
// membuka file
VarBaca.good() : VarBaca.open("COBA.TXT");
“true” jika berhasil membuka
file/membaca data file, “false” jika while(VarBaca.good()) // apakah berhasil membuka
tidak berhasil membuka { // file atau tidak
file/membaca data file. VarBaca >> Teks; // proses membaca data dr file
Hasil: cout << Teks;
}
// Menutup file
VarBaca.close();
}
18. Baca Tulis File
Melakukan penulisan data ke dalam file
- menggunakan operand write()
Sintaks: basic_istream::write (char * buffer, bytesize n);
Contoh program menulis #include <iostream>
data ke file: #include <fstream>
using namespace std;
VarTulis.write(Teks, 15); adalah
proses menulis data ke file berupa void main() {
string yang tersimpan dalam variabel // Mendeklarasikan stream untuk proses output
Teks sebanyak 15 byte. String ofstream VarTulis;
“Kalimat Pertama” terdiri dari 15 char Teks[80];
karakter.
// membuka file
Hasil: VarTulis.open("COBA.TXT");
strcpy(Teks, “Kalimat Pertama”);
VarTulis.write(Teks, 15); // proses menulis data ke file
cout << Teks;
strcpy(Teks,”Kalimat Kedua”);
VarTulis.write(Teks, 13); // proses tulis data ke file
cout << Teks;
Silahkan dicoba jika angka 15 diganti // Menutup file
dengan angka yang berbeda! VarTulis.close();
}
19. Baca Tulis File
Melakukan pembacaan data dari file
- menggunakan operand read()
Sintaks: basic_istream::read (char * buffer, bytesize n);
#include <iostream>
#include <fstream>
using namespace std;
Contoh program membaca
data ke file: void main() {
Jika coba.txt hasil dari program slide // Mendeklarasikan stream untuk proses output
sebelumnya adalah sebagai input file ifstream VarBaca;
maka hasil dilayar adalah: char Teks[80];
// membuka file
VarBaca.open("COBA.TXT");
strcpy(Teks, " "); // mengosongkan variabel Teks
VarBaca.read(Teks, 15); // proses membaca data dr file
cout << Teks << endl;
Silahkan dicoba jika angka 15 strcpy(Teks, " "); // mengosongkan variabel Teks
atau 13 diganti dengan angka VarBaca.read(Teks, 13); // proses baca data dr file
yang berbeda! cout << Teks;
// Menutup file
VarBaca.close();
}
20. Baca Tulis File
Melakukan penulisan data berupa numerik
- menggunakan operand write()
Contoh program menulis #include <iostream>
data ke file: #include <fstream>
using namespace std;
Hasil penyimpanan data numerik ke
file adalah berupa data biner. void main() {
Jika file “Coba.dat” dibuka // Mendeklarasikan stream untuk proses output
menggunakan editor notepad, maka ofstream VarTulis;
akan tampak seperti: float angka = 23.3;
// membuka file
VarTulis.open("COBA.dat");
VarTulis.write((char *) &angka, sizeof(float));
// Menutup file
VarTulis.close();
}
21. Baca Tulis File
Melakukan pembacaan data numerik
- menggunakan operand read()
Contoh program membaca
data dari file: #include <iostream>
#include <fstream>
Jika file “coba.dat” hasil dari using namespace std;
program slide sebelumnya adalah
sebagai input file maka hasil void main() {
dilayar adalah:
// Mendeklarasikan stream untuk proses output
ifstream VarBaca;
float angka;
// membuka file
VarBaca.open("COBA.dat");
Silahkan dicoba menyimpan
data berupa angka/numerik VarBaca.read((char *) &angka, sizeof(float));
lebih dari satu dengan jenis cout << angka << endl;
tipe data yang berbeda (mis. // Menutup file
Int, long int, double) ! Dan VarBaca.close();
anda pikirkan bagaimana
cara membaca data yang }
telah tersimpan tersebut. !!
22. Baca Tulis File
Contoh program menulis dan membaca data ke/dari file:
Contoh penggunaan property getline dan eof dlm pembacaan data
istream& getline( char* pch, int nCount, char delim = 'n' );
#include <iostream>
#include <fstream>
using namespace std;
void main(void) {
Hasil penyimpan di file:
// Mendeklarasikan stream untuk proses input
ifstream VarBaca;
// Mendeklarasikan stream untuk proses output
ofstream VarTulis;
char Teks[80];
// membuka file
VarTulis.open("COBI.TXT");
VarTulis << " C++ mudah Sekali " << endl; //menulis data ke file
VarTulis << " Pemrograman Mudah " << endl; //menulis data ke file
// Menutup file
VarTulis.close();
23. Lanjutan
Baca Tulis File
Hasil pembacaan dari file:
// membuka file
VarBaca.open("COBI.TXT");
//membaca seluruh data dari file, baris per baris
while (!VarBaca.eof()) {
VarBaca.getline(Teks,80, 'n'); //membaca data dari file
cout << Teks << endl;
}
delimiter ‘n’ diganti dengan spacebar ‘ ‘, hasil:
// Menutup file
VarBaca.close();
}
VarBaca.eof() memberikan harga “bukan nol” jika akhir suatu file
telah ditemukan.
VarBaca.getline(Teks,80, 'n'); membaca data karakter yang tersimpan pada file
sampai tanda delimiter ditemukan, delimited ‘n‘ berarti membaca karakter sampai tanda
pindah baris ditemukan.
Coba tanda delimiter ‘n’ anda ganti dengan tanda delimiter spcebar ‘ ‘. Perhatikan hasil
pada layar.
24. Baca Tulis File
Contoh program menulis dan membaca data ke/dari file dg fstream:
Contoh penggunaan property seekg dlm pembacaan data
#include <iostream>
#include <fstream>
using namespace std;
void main(void) {
// Mendeklarasikan stream untuk proses input
ifstream VarBaca;
// Mendeklarasikan stream untuk proses output
ofstream VarTulis;
char Teks[80];
// membuka file
VarTulis.open("COBE.TXT");
VarTulis << "C++ sangat Sekali" << endl; //menulis data ke file
VarTulis << "Pemrograman Mudah" << endl; //menulis data ke file
// Menutup file
VarTulis.close();
25. Lanjutan
Baca Tulis File
// membuka file
VarBaca.open("COBI.TXT");
VarBaca.seekg(17, ios::beg); // set file pointer ke posisi
// 17byte dr awal file
Strcpy(Teks, “ “);
VarBaca.read(Teks, 12); // proses baca data dr file
cout << Teks << “ “;
VarBaca.seekg(0, ios::beg); // set file pointer ke posisi
// 0byte dr awal file
Strcpy(Teks, “ “);
VarBaca.read(Teks, 3); // proses baca data dr file
cout << Teks << “ “;
VarBaca.seekg(28, ios::cur); // set file pointer ke posisi
// 28byte dr posisi saat itu
Strcpy(Teks, “ “);
VarBaca.read(Teks, 5); // proses baca data dr file
cout << Teks << “ “;
26. Lanjutan
Baca Tulis File
VarBaca.seekg(10, ios::beg); // set file pointer ke posisi
// 10byte dr posisi awal
Strcpy(Teks, “ “);
VarBaca.read(Teks, 6); // proses baca data dr file Hasil:
cout << Teks << “ “;
// Menutup file
VarBaca.close();
}
27. Baca Tulis File
Membaca atau menulis data dari/ke sebuah file dapat dilakukan juga
dengan perintah fopen()
Untuk dapat membaca atau menulis data dari/ke sebuah file maka
langkah yang perlu dilakukan adalah:
1. membuka file
- mendefinisikan variabel stream
- melakukan perintah fopen()
2. Melakukan pembacaan atau penulisan data
- menggunakan operand fscanf() atau fprintf()
- menggunakan operand fread() atau fwrite()
perintah fread() atau fwrite() -> informasi ukuran data
yang akan dibaca atau ditulis sangat penting
3. Menutup file
- menggunakan perintah fclose() atau _fcloseall();
28. Baca Tulis File
Contoh program membuka
dan menutup file:
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
void main() {
// Mendeklarasikan stream untuk proses input
FILE *VarBaca;
// membuka file
VarBaca = fopen("COBA.TXT", "r");
if(VarBaca==NULL){
cout << " Error buka file : " << "Coba.txt"
<< endl;
exit(-1); // keluar dari program
}
// Menutup file
fclose(VarBaca);
}
29. Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fprintf() atau fscanf()
#include <iostream.h>
#include <stdio.h>
Contoh program #include <stdlib.h>
menulis data ke file:
void main() {
// Mendeklarasikan stream untuk proses input
FILE *VarTulis;
// membuka file
VarTulis = fopen("COBA.TXT", "w");
if(VarTulis==NULL){
cout << " Error buka file : " << "Coba.txt“ << endl;
exit(-1);
}
fprintf(VarTulis,"C++ mudah Sekalin");
fprintf(VarTulis,"Pemrograman Mudah");
// Menutup file
fclose(VarTulis);
}
30. Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fprintf() atau fscanf()
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
Contoh program
membaca data ke void main() {
file: // Mendeklarasikan stream untuk proses input
FILE *VarBaca;
char Teks[80];
// membuka file
VarBaca = fopen("COBA.TXT", "r");
if(VarBaca==NULL){
cout << " Error buka file : " << "Coba.txt“ << endl;
exit(-1);
}
while(fscanf(VarBaca,"%s",Teks)!=EOF) {
cout << Teks << “ “;
}
// Menutup file
fclose(VarBaca);
}
31. Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fprintf() atau fscanf() dan fgets()
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main() {
// Mendeklarasikan stream untuk proses input
FILE *VarTulis, *VarBaca;
char Teks[80];
// membuka file
VarTulis = fopen("COBA.TXT", "w");
if(VarTulis==NULL){
cout << " Error buka file : " << "Coba.txt"
<< endl;
exit(-1);
}
32. Lanjutan
Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fprintf() atau fscanf() dan fgets()
strcpy(Teks, "Kalimat Pertama");
fprintf(VarTulis,"%20s", Teks); // proses menulis data ke file
cout << Teks;
strcpy(Teks, "Kalimat Kedua");
fprintf(VarTulis,"%20s", Teks); // proses menulis data ke file
cout << Teks;
// Menutup file
fclose(VarTulis);
33. Lanjutan
Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fprintf() atau fscanf() dan fgets()
// membuka file
VarBaca = fopen("COBA.TXT", "r");
if(VarBaca==NULL){
cout << " Error buka file : " << "Coba.txt"
<< endl;
exit(-1);
}
while( fgets(Teks, 21, VarBaca) != NULL ) {
cout << Teks << endl;
}
// Menutup file
fclose(VarBaca);
}
34. Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fread() atau fwrite()
Sintaks: fwrite (char * buffer, size t, count n, iobuf *);
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
Contoh program menulis #include <string.h>
data ke file:
void main() {
// Mendeklarasikan stream untuk proses input
FILE *VarTulis;
char Teks[80];
// membuka file
VarTulis = fopen("COBA.TXT", "w");
if(VarTulis==NULL){
cout << " Error buka file : " << "Coba.txt"
<< endl;
exit(-1);
}
35. Lanjutan .
Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fread() atau fwrite()
Sintaks: fwrite (char * buffer, size t, count n, iobuf *);
Contoh program menulis data ke file:
// membuka file
strcpy(Teks, "Kalimat Pertama");
fwrite(Teks,sizeof(char),20, VarTulis); // proses menulis data ke file
cout << Teks;
strcpy(Teks, "Kalimat Kedua");
fwrite(Teks,sizeof(char),20, VarTulis); // proses menulis data ke file
cout << Teks;
// Menutup file
fclose(VarTulis);
}
36. Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fread() atau fwrite()
Sintaks: fread (char * buffer, size t, count n, iobuf *);
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
Contoh program #include <string.h>
Membaca data ke file:
void main() {
// Mendeklarasikan stream untuk proses input
FILE *VarBaca;
char Teks[80];
// membuka file
VarBaca = fopen("COBA.TXT", "r");
if(VarBaca==NULL){
cout << " Error buka file : " << "Coba.txt"
<< endl;
exit(-1);
}
37. Lanjutan .
Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fread() atau fwrite()
Sintaks: fread (char * buffer, size t, count n, iobuf *);
Contoh program
Membaca data ke file:
fread(Teks,sizeof(char),20, VarBaca); // proses menulis data ke file
cout << Teks << endl;
fread(Teks,sizeof(char),20, VarBaca); // proses menulis data ke file
cout << Teks << endl;
// Menutup file
fclose(VarBaca);
}
38. Baca Tulis File
Melakukan penulisan data berupa numerik
- menggunakan operand fwrite()
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
Contoh program void main() {
Menulis data ke file: // Mendeklarasikan stream untuk proses input
FILE *VarTulis;
float angka = 23.3;
// membuka file
VarTulis = fopen("COBA.DAT", "w");
if(VarTulis==NULL){
cout << " Error buka file : " << "Coba.txt“ << endl;
exit(-1);
}
fwrite(&angka,sizeof(float),1, VarTulis); // proses menulis data ke file
cout << angka << endl;
// Menutup file
fclose(VarTulis);
}
39. Baca Tulis File
Melakukan penulisan data berupa numerik
- menggunakan operand fwrite()
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
Contoh program void main() {
Menulis data ke file: // Mendeklarasikan stream untuk proses input
FILE *VarBaca;
float angka;
// membuka file
VarBaca = fopen("COBA.DAT", "r");
if(VarBaca==NULL){
cout << " Error buka file : " << "Coba.txt" << endl;
exit(-1);
}
fread(&angka,sizeof(float),1, VarBaca); // proses menulis data ke file
cout << angka << endl;
// Menutup file
fclose(VarBaca);
}
40. Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fread() atau fwrite() dan fungsi fseek()
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main() {
// Mendeklarasikan stream untuk proses input
FILE *VarTulis, *VarBaca;
char Teks[80];
// membuka file
VarTulis = fopen("COBA.TXT", "w");
if(VarTulis==NULL){
cout << " Error buka file : " << "Coba.txt"
<< endl;
exit(-1);
}
41. Lanjutan .
Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fread() atau fwrite() dan fungsi fseek()
strcpy(Teks, "Kalimat Pertama");
fprintf(VarTulis,"%20s", Teks); // proses menulis data ke file
cout << Teks;
strcpy(Teks, "Kalimat Kedua");
fprintf(VarTulis,"%20s", Teks); // proses menulis data ke file
cout << Teks;
// Menutup file
fclose(VarTulis);
42. Lanjutan .
Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fread() atau fwrite() dan fungsi fseek()
// membuka file
VarBaca = fopen("COBA.TXT", "r");
if(VarBaca==NULL){
cout << " Error buka file : " << "Coba.txt"
<< endl;
exit(-1);
}
while( fgets(Teks, 21, VarBaca) != NULL ) {
cout << Teks << endl;
}
fseek(VarBaca, -40, SEEK_END);
fgets(Teks, 21, VarBaca);
// Menutup file
fclose(VarBaca);
}