input file dalam c++
DESCRIPTION
TRANSCRIPT
Input/Output with files
Rena Widita
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.
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()
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.
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:
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:
to open a file with a stream object we use its member function open():
open (filename, mode);
• 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);
• 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 */ }
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().
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:
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).
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.
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 followingmember functions:
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();
}
Baca Tulis File
Baca Tulis File
#include <iostream>
#include <fstream>
using namespace std;
void main() {
// Mendeklarasikan stream untuk proses output
ofstream VarTulis;
// membuka file
VarTulis.open("COBA.TXT");
VarTulis << “C++ mudah Sekali” << endl;;
VarTulis << “Pemrograman Mudah “ << endl;
// Menutup file
VarTulis.close();
}
Contoh program menulis
data ke file:Data file yang bernama
“COBA.TXT” akan disimpan pada
folder di mana folder tempat
program file berada. Atau informasi
drive dan folder harus diinputkan,
contoh:
“C://DATA//COBA.TXT”
Jika file “Coba.txt” kita buka
dengan editor notepad, akan
tampak seperti:
Melakukan penulisan data ke dalam file
- menggunakan operand <<
Melakukan pembacaan data dari file
- menggunakan operand >>
Baca Tulis File
#include <iostream>
#include <fstream>
using namespace std;
void main() {
// Mendeklarasikan stream untuk proses output
ifstream VarBaca;
char Teks[80];
// membuka file
VarBaca.open("COBA.TXT");
VarBaca >> Teks; // proses membaca data dr file (1 string/kata)
cout << Teks << “ “; // “ “ -> memisahkan dg teks berikutnya
VarBaca >> Teks; // proses baca data dr file (1 string/kata)
cout << Teks;
// Menutup file
VarBaca.close();
}
Contoh program membaca
data dari file:
Data file yang bernama
“COBA.TXT” harus sudah
ada di folder tempat program file
berada. Jika tidak maka informasi
drive dan folder harus diinputkan,
contoh:
“C://DATA//COBA.TXT”
VarBaca >> Teks; menghasilkan
satu string/kata dibaca dari file.
Jika coba.txt hasil dari program slide
sebelumnya adalah sebagai input
file maka hasil dilayar adalah:
Baca Tulis File
Melakukan pembacaan data dari file
- menggunakan operand >> dan while()
#include <iostream>
#include <fstream>
using namespace std;
void main() {
// Mendeklarasikan stream untuk proses output
ifstream VarBaca;
char Teks[80];
// membuka file
VarBaca.open("COBA.TXT");
while(VarBaca.good()) // apakah berhasil membuka
{ // file atau tidak
VarBaca >> Teks; // proses membaca data dr file
cout << Teks;
}
// Menutup file
VarBaca.close();
}
Contoh program membaca
data dari file:
Data file yang bernama
“COBA.TXT” harus sudah
ada di folder tempat program file
berada. Jika tidak maka informasi
drive dan folder harus diinputkan,
contoh:
“C://DATA//COBA.TXT”
VarBaca.good() :
“true” jika berhasil membuka
file/membaca data file, “false” jika
tidak berhasil membuka
file/membaca data file.
Hasil:
Baca Tulis File
#include <iostream>
#include <fstream>
using namespace std;
void main() {
// Mendeklarasikan stream untuk proses output
ofstream VarTulis;
char Teks[80];
// membuka file
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;
// Menutup file
VarTulis.close();
}
Melakukan penulisan data ke dalam file
- menggunakan operand write()
Contoh program menulis
data ke file:
VarTulis.write(Teks, 15); adalah
proses menulis data ke file berupa
string yang tersimpan dalam variabel
Teks sebanyak 15 byte. String
“Kalimat Pertama” terdiri dari 15
karakter.
Hasil:
Silahkan dicoba jika angka 15 diganti
dengan angka yang berbeda!
Sintaks: basic_istream::write (char * buffer, bytesize n);
Baca Tulis File
#include <iostream>
#include <fstream>
using namespace std;
void main() {
// Mendeklarasikan stream untuk proses output
ifstream VarBaca;
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;
strcpy(Teks, " "); // mengosongkan variabel Teks
VarBaca.read(Teks, 13); // proses baca data dr file
cout << Teks;
// Menutup file
VarBaca.close();
}
Melakukan pembacaan data dari file
- menggunakan operand read()
Sintaks: basic_istream::read (char * buffer, bytesize n);
Contoh program membaca
data ke file:
Jika coba.txt hasil dari program slide
sebelumnya adalah sebagai input file
maka hasil dilayar adalah:
Silahkan dicoba jika angka 15
atau 13 diganti dengan angka
yang berbeda!
Melakukan penulisan data berupa numerik
- menggunakan operand write()
Baca Tulis File
#include <iostream>
#include <fstream>
using namespace std;
void main() {
// Mendeklarasikan stream untuk proses output
ofstream VarTulis;
float angka = 23.3;
// membuka file
VarTulis.open("COBA.dat");
VarTulis.write((char *) &angka, sizeof(float));
// Menutup file
VarTulis.close();
}
Contoh program menulis
data ke file:
Hasil penyimpanan data numerik ke
file adalah berupa data biner.
Jika file “Coba.dat” dibuka
menggunakan editor notepad, maka
akan tampak seperti:
Melakukan pembacaan data numerik
- menggunakan operand read()
Baca Tulis File
#include <iostream>
#include <fstream>
using namespace std;
void main() {
// Mendeklarasikan stream untuk proses output
ifstream VarBaca;
float angka;
// membuka file
VarBaca.open("COBA.dat");
VarBaca.read((char *) &angka, sizeof(float));
cout << angka << endl;
// Menutup file
VarBaca.close();
}
Contoh program membaca
data dari file:
Jika file “coba.dat” hasil dari
program slide sebelumnya adalah
sebagai input file maka hasil
dilayar adalah:
Silahkan dicoba menyimpan
data berupa angka/numerik
lebih dari satu dengan jenis
tipe data yang berbeda (mis.
Int, long int, double) ! Dan
anda pikirkan bagaimana
cara membaca data yang
telah tersimpan tersebut. !!
Baca Tulis File
#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("COBI.TXT");
VarTulis << " C++ mudah Sekali " << endl; //menulis data ke file
VarTulis << " Pemrograman Mudah " << endl; //menulis data ke file
// Menutup file
VarTulis.close();
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' );
Hasil penyimpan di file:
Baca Tulis 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;
}
// Menutup file
VarBaca.close();
}
Lanjutan $
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.
Hasil pembacaan dari file:
delimiter ‘\n’ diganti dengan spacebar ‘ ‘, hasil:
Baca Tulis File
#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();
Contoh program menulis dan membaca data ke/dari file dg fstream:
Contoh penggunaan property seekg dlm pembacaan data
Baca Tulis FileLanjutan $
// 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 << “ “;
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
cout << Teks << “ “;
// Menutup file
VarBaca.close();
}
Baca Tulis FileLanjutan $
Hasil:
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();
Contoh program membuka
dan menutup file:
Baca Tulis File
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
void main() {
// Mendeklarasikan stream untuk proses inputFILE *VarBaca;
// membuka fileVarBaca = fopen("COBA.TXT", "r");
if(VarBaca==NULL){
cout << " Error buka file : " << "Coba.txt"
<< endl;
exit(-1); // keluar dari program}
// Menutup filefclose(VarBaca);
}
Baca Tulis File
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
void main() {
// Mendeklarasikan stream untuk proses inputFILE *VarTulis;
// membuka fileVarTulis = fopen("COBA.TXT", "w");
if(VarTulis==NULL){
cout << " Error buka file : " << "Coba.txt“ << endl;
exit(-1);
}
fprintf(VarTulis,"C++ mudah Sekali\n");
fprintf(VarTulis,"Pemrograman Mudah");
// Menutup filefclose(VarTulis);
}
Contoh program
menulis data ke file:
Melakukan pembacaan atau penulisan data
- menggunakan operand fprintf() atau fscanf()
Baca Tulis File
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
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);
}
while(fscanf(VarBaca,"%s",Teks)!=EOF) {
cout << Teks << “ “;
}
// Menutup file
fclose(VarBaca);
}
Contoh program
membaca data ke
file:
Melakukan pembacaan atau penulisan data
- menggunakan operand fprintf() atau fscanf()
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);
}
Baca Tulis File
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);
Lanjutan $
Melakukan pembacaan atau penulisan data
- menggunakan operand fprintf() atau fscanf() dan fgets()
Baca Tulis File
// 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);
}
Lanjutan $
Melakukan pembacaan atau penulisan data
- menggunakan operand fprintf() atau fscanf() dan fgets()
Baca Tulis File
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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);
}
Melakukan pembacaan atau penulisan data
- menggunakan operand fread() atau fwrite()
Contoh program menulis
data ke file:
Sintaks: fwrite (char * buffer, size t, count n, iobuf *);
Baca Tulis 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);
}
Melakukan pembacaan atau penulisan data
- menggunakan operand fread() atau fwrite()
Contoh program menulis data ke file:
Sintaks: fwrite (char * buffer, size t, count n, iobuf *);
Lanjutan$.
Baca Tulis File
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
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);
}
Melakukan pembacaan atau penulisan data
- menggunakan operand fread() atau fwrite()
Contoh program
Membaca data ke file:
Sintaks: fread (char * buffer, size t, count n, iobuf *);
Baca Tulis 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);
}
Melakukan pembacaan atau penulisan data
- menggunakan operand fread() atau fwrite()
Contoh program
Membaca data ke file:
Sintaks: fread (char * buffer, size t, count n, iobuf *);
Lanjutan$.
Melakukan penulisan data berupa numerik
- menggunakan operand fwrite()
Baca Tulis File
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
void main() {
// Mendeklarasikan stream untuk proses inputFILE *VarTulis;
float angka = 23.3;
// membuka fileVarTulis = 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);
}
Contoh program
Menulis data ke file:
Melakukan penulisan data berupa numerik
- menggunakan operand fwrite()
Baca Tulis File
#include <iostream.h>
#include <stdio.h>
#include <stdlib.h>
void main() {
// 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);
}
Contoh program
Menulis data ke file:
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);
}
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);
Lanjutan$.
// 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);
}
Baca Tulis File
Melakukan pembacaan atau penulisan data
- menggunakan operand fread() atau fwrite() dan fungsi fseek()
Lanjutan$.