bab 12 file_manipulation
DESCRIPTION
algoritma dan struktur data - file manipulationTRANSCRIPT
FILE MANIPULATIONFILE MANIPULATION
PENGANTAR FILE
File digunakan sebagai penyimpanan data eksternal selain memori komputer.
Tempat penyimpanan eksternal ini bersifat permanen (non-volatile) dan biasanya berukuran besar dengan tujuan untuk dibaca kembali datadatanya.
Operasi-operasi terhadap file pasti berkaitan dengan Input (menulis) dan Output (menampilkan) serta berbagai hal lain seperti mengecekkeberadaan file, ukuran file, dan lain-lain.
Operasi untuk mengolah file membutuhkan buffer untuk menampung informasi yang berkenaan dengan file tersebut.
JENIS FILE :FILE TEKS
File TeksFile teks adalah file yang berisi data-data
ASCII sehingga dapat ditampilkan ke layar apa adanya.
Satu karakter ASCII dalam file teks berukuran 2 bytes.
Misalnya sebuah file teks berisi 1000 karakter berarti berukuran 2000 bytes.
JENIS FILE :FILE BINER
Ganti dengan yang ada di bukuFile Biner File yang data-datanya berupa data biner dan
berupa byte stream sehingga tidak dapat ditampilkan apa adanya dilayar.
Satu karakter berukuran 1 byte, sedangkan nilai bukan karakter akan disimpan sesuai dengan ukuran microprocessor.
Ukuran tergantung pada ketentuan microprocessor, bukan pada jumlah digit bilangan.
BACA TULIS FILEBACA TULIS FILE
Membaca dan menulis file dalam bahasa C Membaca dan menulis file dalam bahasa C membutuhkan 3 langkah yaitu:membutuhkan 3 langkah yaitu: Membuka file. Membuka file. Mengerjakan membaca dan menulisMengerjakan membaca dan menulis Menutup fileMenutup file
FILE dalam C dimanipulasi dengan menggunakan
header file stdio.h atau fstream.h
PENGGUNAAN STDIO.H
FILEFILE
Deklarasikan FILE seperti berikut:
FILE *f
Berarti menyiapkan buffer area dan di-assign ke pointer bernama f
FILE SEBAGAI FILE SEBAGAI SEBUAH STRUCTSEBUAH STRUCT
FILE adalah sebuah struct yang didefinisikan pada stdio.h sebagai berikut:
typedef struct {
unsigned char *curp; /* Current active pointer */unsigned char *buffer; /* Data transfer buffer */int level; /* fill/empty level of buffer */int bsize; /* Buffer size */unsigned short istemp; /* Temporary file indicator */unsigned short flags; /* File status flags */short token; /* Used for validity checking */char fd; /* File descriptor */unsigned char hold; /* Ungetc char if no buffer */
} FILE;
MEMBUKA FILE(1)
Suatu file dalam disk harus dalam keadaan terbuka terlebih dahulu baru dapat diakses.
FILE *fopen(const char *filename, const char *mode)
Kembalian dari fungsi fopen adalah nilai pointer file atau NULL jika Pembukaan file gagal
Filename adalah nama file Dengan parameter mode adalah:
r - open for readingw - open for writing (file need not exist)a - open for appending (file need not exist)r+ - open for reading and writing, start at beginningw+ - open for reading and writing (overwrite file)a+ - open for reading and writing (append if file exists)
MEMBUKA FILE(2)
File dapat dibuka sebagai file teks (t) atau file biner (b) File teks menggunakan parameter tambahan menjadi rt,
wt, at,r+t, w+t, dan a+t File biner menggunakan parameter tambahan menjadi
rb, wb, ab,r+b, w+b, dan a+b Defaultnya adalah mode teks (t)
Contoh penggunaan:1 FILE *fp;2 fp=fopen("c:\\test.txt", "r");3 f (fp==NULL) 4 printf(“Error, file tidak dapat dibuka!”);
MENUTUP FILE
int fclose(FILE *a_file);int fcloseall(void);
Nilai kembalian int akan berisi 0 jika berhasil atau -1 (EOF) jika gagal
fcloseall akan menutup seluruh stream yang aktif Pada Windows, kembalian dari nilai ini tidak terlalu diperlukan
karena di Windows tidak diperlukan untuk mengetahui status suatu program.
Contoh penggunaan:1 FILE *fp;2 fp=fopen("c:\\test.txt", "r");3 if (fp==NULL) printf(“Error, file tidak dapat dibuka!”);4 fclose(fp);
FUNGSI-FUNGSI FILE FUNGSI-FUNGSI FILE STDIO.HSTDIO.H
Untuk menulis ke file dalam format tertentu: int fprintf(fp, "Testing...\n"); jika berhasil akan dikembalikan jumlah byte yang dituliskan
sedangkan jika gagal dikembalikan EOF
Untuk membaca dari file dalam format field tertentu: int fscanf(fp, "Testing...\n"); jika berhasil akan dikembalikan jumlah field yang dibaca sedangkan
jika gagal dikembalikan EOF
Untuk menulis karakter ke file teks: int fputc( int c, FILE *fp ); jika berhasil akan dikembalikan karakter c sedangkan jika gagal
dikembalikan EOF
FUNGSI-FUNGSI FILE FUNGSI-FUNGSI FILE STDIO.H(2)STDIO.H(2)
Untuk membaca file teks perkarakter: int fgetc (FILE *fp); jika berhasil akan dikembalikan karakter c sedangkan jika gagal
dikembalikan EOF
Untuk meletakkan nilai integer ke file: int putw(int w, FILE *fp); jika berhasil akan dikembalikan integer w sedangkan jika gagal
dikembalikan EOF
Untuk membaca nilai integer: int getw(FILE *fp); jika berhasil akan dikembalikan integer w sedangkan jika gagal
dikembalikan EOF
FUNGSI-FUNGSI FILE FUNGSI-FUNGSI FILE STDIO.H(3)STDIO.H(3)
Untuk menulis string ke file tanpa ada karakter NULL dan newline: int fputs(const char *s,FILE *fp); jika berhasil akan dikembalikan string s sedangkan jika gagal
dikembalikan EOF
Untuk membaca string dari file sebanyak n karakter atau bertemu karakter ‘\n’: char *fgets(const char *s,int n,FILE *fp); jika berhasil akan dikembalikan string s sedangkan jika gagal
dikembalikan EOF
Untuk mengetahui akhir sebuah file stream: int feof(FILE *fp); jika berhasil akan dikembalikan nilai integer selain 0.
PROGRAM MEMBACA FILE:PROGRAM MEMBACA FILE:Program 1Program 1
Program 1 adalah membaca data dari file dan meng-outputkan Program 1 adalah membaca data dari file dan meng-outputkan hasilnya ke layarhasilnya ke layar
11 #include <stdio.h>#include <stdio.h>22 int main()int main()33 {{44 char filename[] = "c:/kuliah.txt";char filename[] = "c:/kuliah.txt";55 char user[10]; /* One extra for nul char. */char user[10]; /* One extra for nul char. */66 int idNum;int idNum;77 FILE *ifp;FILE *ifp;88 /* Open file for input *//* Open file for input */99 ifp = fopen(filename,"r");ifp = fopen(filename,"r");1010 while (fscanf (ifp, "%s", user) != EOF) {while (fscanf (ifp, "%s", user) != EOF) {1111 printf("%s ", user);printf("%s ", user);1212 }}1313 }}
PROGRAM MEMBACA FILE(2)PROGRAM MEMBACA FILE(2)
File input dari program 2 (kuliah.txt) berisi File input dari program 2 (kuliah.txt) berisi
dengan baris yang memuat dengan baris yang memuat username username dan dan score score
seperti di bawah ini:seperti di bawah ini:
Dewi 90Dewi 90
Gita 80 Gita 80
Dengan catatan setiap username berisi tidak lebih Dengan catatan setiap username berisi tidak lebih
dari 9 karakterdari 9 karakter
PROGRAM MEMBACA FILE(2)PROGRAM MEMBACA FILE(2)11 #include <stdio.h>#include <stdio.h>22 int main()int main()33 {{44 char filename[] = "c:/kuliah.txt";char filename[] = "c:/kuliah.txt";55 char username[9]; /* One extra for nul char. */char username[9]; /* One extra for nul char. */66 int score;int score;77 FILE *ifp;FILE *ifp;88 /* Open file for input *//* Open file for input */99 ifp = fopen(filename,"r");ifp = fopen(filename,"r");
1010 while (fscanf(ifp, "%s %d", username, &score) != EOF) {while (fscanf(ifp, "%s %d", username, &score) != EOF) {1111 printf("%s %d\n", username, score);printf("%s %d\n", username, score);1212 }}1313 }}
PROGRAM MENULIS FILEPROGRAM MENULIS FILE11 #include <stdio.h>#include <stdio.h>22 int main()int main()33 {{44 char filename[] = "c:/kuliah.txt";char filename[] = "c:/kuliah.txt";55 char name[30];char name[30];66 int idNum;int idNum;
77 printf("Masukkan nama:");printf("Masukkan nama:");88 scanf("%s",&name);scanf("%s",&name);99 printf("Masukkan nomor id:");printf("Masukkan nomor id:");1010 scanf("%d",&idNum);scanf("%d",&idNum);
// bersambung// bersambung
PROGRAM MENULIS FILEPROGRAM MENULIS FILE
1111 FILE *ofp;FILE *ofp;1212 ofp = fopen(filename,"w");ofp = fopen(filename,"w");1313 /* Write out data *//* Write out data */1414 fprintf(ofp,"%s %d\n",name, idNum);fprintf(ofp,"%s %d\n",name, idNum);1515 /* Close Files *//* Close Files */1616 fclose(ofp);fclose(ofp);1717 return 0;return 0;1818 }}
PROGRAM MENULIS FILEPROGRAM MENULIS FILE11 #include <stdio.h>#include <stdio.h>22 int main()int main()33 {{44 char ifilename[] = "c:/kuliah.txt";char ifilename[] = "c:/kuliah.txt";55 char ofilename[] = "c:/kuliah2.txt";char ofilename[] = "c:/kuliah2.txt";66 char name[30];char name[30];77 int idNum;int idNum;88 FILE *ofp, *ifp;FILE *ofp, *ifp;99 /* Open file for input *//* Open file for input */1010 ifp = fopen(ifilename,"r");ifp = fopen(ifilename,"r");1111 /* Read data *//* Read data */1212 fscanf(ifp,"%s %d",name,&idNum);fscanf(ifp,"%s %d",name,&idNum);
PROGRAM MENULIS FILEPROGRAM MENULIS FILE
1313 /* Open file for output *//* Open file for output */1414 ofp = fopen(ofilename,"w");ofp = fopen(ofilename,"w");1515 /* Write out data *//* Write out data */1616 fprintf(ofp,"%s %d\n",name, idNum);fprintf(ofp,"%s %d\n",name, idNum);1717 /* Close Files *//* Close Files */1818 fclose(ifp);fclose(ifp);1919 fclose(ofp);fclose(ofp);2020 return 0;return 0;2121 }}
MANIPULASI FILE DENGAN FSTREAM.H
MENDEFINISIKAN FILEMENDEFINISIKAN FILE
Mendefinisikan objek fileMendefinisikan objek file
Bentuk pernyataannya adalah sebagai berikut Bentuk pernyataannya adalah sebagai berikut
untuk input:untuk input:ifstream nama_variabel_file;
nama_variabel_file_input.open(“nama_file.txt”);
untuk output:untuk output:ofstream nama_variabel_file;
nama_variabel_file_output.open(“nama_file.txt”);
FUNGSI-FUNGSI FILEFUNGSI-FUNGSI FILEFSTREAM.HFSTREAM.H
Input operationsInput operations cin.get(char &ch) cin.get(char &ch)
Puts the next input character in the variable ch. Returns an integer value, which is zero if it Puts the next input character in the variable ch. Returns an integer value, which is zero if it encountered a problem (e.g. end of file). encountered a problem (e.g. end of file).
cin.getline(char *buffer, int length) cin.getline(char *buffer, int length) Reads characters into the string buffer, stopping when (a) it has read length-1 characters or Reads characters into the string buffer, stopping when (a) it has read length-1 characters or
(b) when it finds an end-of-line character ('\n') or the end of the file. Stores a null character ('\(b) when it finds an end-of-line character ('\n') or the end of the file. Stores a null character ('\0') after the last character read. 0') after the last character read.
cin.read(char *buffer, int n) cin.read(char *buffer, int n) Reads n bytes (or until the end of the file) from the stream into the buffer. Reads n bytes (or until the end of the file) from the stream into the buffer.
cin.gcount() cin.gcount() Returns the number of characters read by a preceding get, getline, or read command. Returns the number of characters read by a preceding get, getline, or read command.
cin.ignore(int n) cin.ignore(int n) Remove the next n characters (or until end of file) from the input stream, throwing them Remove the next n characters (or until end of file) from the input stream, throwing them
away into the Great Bit Bucket. away into the Great Bit Bucket. cin.putback(char ch) cin.putback(char ch)
Puts character ch back onto the stream. Bad things will happen if this character is not the Puts character ch back onto the stream. Bad things will happen if this character is not the one most recently extracted from the stream. These operations all return zero if something one most recently extracted from the stream. These operations all return zero if something goes wrong, e.g. they hit the end of the file. Therefore, they can be used as the condition in goes wrong, e.g. they hit the end of the file. Therefore, they can be used as the condition in an if statement or while loop. an if statement or while loop.
cin.get() cin.get() Returns the next character in the stream. Returns the next character in the stream.
FUNGSI-FUNGSI FILEFUNGSI-FUNGSI FILEFSTREAM.H(2)FSTREAM.H(2)
cin.peek() cin.peek() Returns the next character in the stream but does not remove it from the stream. Returns the next character in the stream but does not remove it from the stream.
The following functions can be used to test the status of a stream. They return an The following functions can be used to test the status of a stream. They return an integer, which is either zero or non-zero. integer, which is either zero or non-zero.
cin.good() cin.good() Returns 0 if the stream has encountered problems such as reading the end of file, non-Returns 0 if the stream has encountered problems such as reading the end of file, non-
existent file. existent file. cin.bad() cin.bad()
Returns non-zero value if the stream is totally unusable, e.g. the file cannot be opened (but Returns non-zero value if the stream is totally unusable, e.g. the file cannot be opened (but not if the stream has merely hit the end of the file). not if the stream has merely hit the end of the file).
cin.eof() cin.eof() Returns a non-zero value if the stream has hit the end of the file. Returns a non-zero value if the stream has hit the end of the file.
. . OUTPUT OPERATIONSOUTPUT OPERATIONS Other options for writing data to an output stream are: Other options for writing data to an output stream are: cout.put(char ch) cout.put(char ch)
Puts ch onto the stream. Puts ch onto the stream. cout.write(char *str, int n) cout.write(char *str, int n)
Puts n characters onto the stream, reading them from the string str. Puts n characters onto the stream, reading them from the string str.
PROGRAM MEMBACA FILEPROGRAM MEMBACA FILE11 #include <iostream.h>#include <iostream.h>22 #include <fstream.h>#include <fstream.h>33 void main(){void main(){44 ifstream f("c:\\kuliah.txt");ifstream f("c:\\kuliah.txt");55 const int MAKS = 80;const int MAKS = 80;66 char buf[MAKS+1];char buf[MAKS+1];77 while(f){while(f){88 f.getline(buf,MAKS);f.getline(buf,MAKS);99 cout<<buf<<endl;cout<<buf<<endl;1010 }}1111 f.close();f.close();1212 }}
PROGRAM MENULIS FILEPROGRAM MENULIS FILE
1 #include <iostream.h>2 #include <fstream.h>3 void main(){4 ofstream f;5 f.open("c:\\kuliah.txt");6 cout<<”Penulisan dimulai...”<<endl;7 f<<“belajar"<<endl;8 f<<“manipulasi file"<<endl;9 cout<<”Penulisan selesai.”<<endl;10 f.close();11 }