Minggu, 20 November 2011

LANJUTAN ARTIKEL FUNGSI C++ FILE I/O IN C++

Closing a file
Ketika kita mengakhiri operasi input/output pada file, kita
harus menutup file tersebut.
Dalam C++ terdapat fungsi close()untuk menutup file
yang telah dibuka.
ofstream myfile ("example.txt");
Kalau sudah memanggil fungsi close(), jika untuk membuka
file lagi, maka harus dipanggil fungsi open() kembali.
myfile.close();

Text files
Untuk stream text files, kita tidak memasukkan flag
ios::binary dalam mode pembukanya.
File-file tersebut didesain untuk memasukkan text dan lalu
kita input atau output karakter-karakter dari/ke file
tersebut.
Contoh Text Files
1234567
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;
int main () {
ofstream myfile ("example.txt");
[file example.txt]
This is a line.
This is another line.
789
10
11
12
13
14
15
16
if (myfile.is_open()) {
myfile << "This is a line.\n";
myfile << "This is another line.\n";
myfile.close();
} else
cout << "Unable to open file";
return 0;
}
Input data menggunakan cin
123456789
10
11
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
This is a line.
This is another line.
12
13
14
15
16
17
18
19
20
21
22
23
if (myfile.is_open()) {
while ( myfile.good() ) {
getline (myfile,line);
cout << line << endl;
}
myfile.close();
} else
cout << "Unable to open file";
return 0;
}

References
http://www.functionx.com/cpp/articles/filestreaming.htm
http://www.cplusplus.com/doc/tutorial/files/
http://www.cstutoringcenter.com/tutorials/cpp/cpp9.php

0 komentar:

Posting Komentar

Pages

Sample Text

Diberdayakan oleh Blogger.

News

Recent Posts

Download