File Handling Pemrograman File Membuat suatu file baru
File Handling
Pemrograman File • • • Membuat suatu file baru Membuka suatu file Menutup suatu file Membaca suatu file Menutup suatu file
Lingkup file • Secara umum pada C, semua piranti komputer bisa dianggap sebagai ‘file’ • Lingkup file yang akan dibahas pada materi ini: – Kumpulan data yang disimpan pada media penyimpan (disk)
Text & Binary File • Text file hanya berisi teks, terdiri dari karakter -karakter ascii, tanpa ada formatting. Contoh: file teks(dibuat pakai notepad), file source code • Binary file berisi data biner, baik berupa data ascii maupun formatting. Contoh : file MS word (ada teks dan formatting: cetak tebal, cetak miring, tabel dsb) • Cara menentukan file teks/biner: buka file tsb pakai notepad(teks editor), kalau file tsb bisa dibaca, berarti file teks. kalau tidak(tidak beraturan), berarti file biner
Bagaimana kita memperlakukan file di C: DISK Proses open file: Membuat link antara File dgn pointer to file link File yg tersimpan di disk MEMORI Pointer to File : Alokasi Memori komputer Utk memproses file Proses close file: Memutus link file - pointer
File handling in C • In C we use FILE * to represent a pointer to a file. • fopen is used to open a file. It returns the special value NULL to indicate that it couldn't open the file. FILE *fptr; char filename[]= "file 2. dat"; fptr= fopen (filename, "w"); if (fptr == NULL) { fprintf (stderr, “ERROR”); /* DO SOMETHING */ }
Opening a File • A file must be “opened” before it can be used. FILE *fp; – – : fp = fopen (filename, mode); fp is declared as a pointer to the data type FILE. filename is a string - specifies the name of the file. fopen returns a pointer to the file which is used in all subsequent file operations. mode is a string which specifies the purpose of opening the file: “r” : : open the file for reading only “w” : : open the file for writing only “a” : : open the file for appending data to it
Fungsi fopen • Berfungsi membuat link antara file (umumnya di disk) dengan memori (pointer to file) • Format: pointer_to file = fopen(namafile, mode) ; • Jika namafile sudah ada, maka komputer tinggal membuat link saja • Jika namafile belum ada, maka komputer akan membuat (create) file tersebut dahulu
Modes for opening text files • The second argument of fopen is the mode in which we open the text file. There are three • "r" opens a file for reading(read only!) • "w" creates a file for writing - and writes over all previous contents (deletes the file so be careful! previous contents are erased) • "a" opens a file for appending - writing on the end of the file
Other modes • “r+” : open text file for read/write • “w+” : create text file for read/write • “a+” : append to or create a text file for read/write
Gambaran efek masing 2 mode pada suatu file teks Sebelum fopen abcdefghi w, w+ (ada isinya) a, a+ Setelah fopen abcdefghi (kosong) Sebelum fopen abcdefghi Setelah fopen r, r+ Setelah fopen abcdefghi Pointer file Ada disini
Closing a File • After all operations on a file have been completed, it must be closed. – Ensures that all file data stored in memory buffers are properly written to the file. • General format: fclose (file_pointer) ; FILE *xyz ; xyz = fopen (“test”, “w”) ; ……. fclose (xyz) ;
Writing to a file using fprintf • fprintf works just like printf and sprintf except that its first argument is a file pointer. FILE *fptr; fptr= fopen ("file. dat", "w"); /* Check it's open */ fprintf (fptr, "Hello World!n"); fclose(fptr);
Percobaan • Buat sembarang file teks dengan notepad dan namai file tsb dengan nama “file. dat” • Isilah file tsb dengan sembarang karakter misalnya “abcbdef……” • Buatlah program seperti pada slide sebelumnya • Letakkan file teks tsb satu folder dengan program • Eksekusi program tsb, buka file. dat dengan notepad apa yg terjadi dengan isi file nya? • Gantilah dengan mode yang lain, amati hasilnya
Reading from a file using fgets • fgets is a better way to read from a file • We can read into a string using fgets FILE *fptr; char line [1000]; /* Open file and check it is open */ while (fgets(line, 1000, fptr) != NULL) { printf ("Read line %sn", line); } fgets takes 3 arguments, a string, a maximum number of characters to read and a file pointer. It returns NULL if there is an error (such as EOF)
fscanf and fprintf • We can also use the file versions of scanf and printf, called fscanf and fprintf. • General format: fscanf (file_pointer, control_string, list) ; fprintf (file_pointer, control_string, list) ; • Examples: fscanf (fp, “%d %s %f”, &roll, dept_code, &cgpa) ; fprintf (out, “n. The result is: %d”, xyz) ;
Other Read/Write Operations on Files • The simplest file input-output (I/O) function are getc and putc. • getc is used to read a character from a file and return it. char ch; FILE *fp; …. . ch = getc (fp) ; – getc will return an end-of-file marker EOF, when the end of the file has been reached. • putc is used to write a character to a file. char ch; FILE *fp; …… putc (c, fp) ;
Contoh soal • Buatlah program untuk meng-convert huruf-huruf pada suatu text file menjadi uppercase!
Example : : convert a text file to all UPPERCASE main() { FILE *in, *out ; char c ; in = fopen (“infile. dat”, “r”) ; out = fopen (“outfile. dat”, “w”) ; while ((c = getc (in)) != EOF) putc (toupper (c), out); fclose (in) ; fclose (out) ; }
Checking EOF (end of file) • How to check EOF condition when using fscanf? – Use the function feof if (feof (fp)) printf (“n Reached end of file”) ; • How to check successful open? – For opening in “r” mode, the file must exist. if (fp == NULL) printf (“n Unable to open file”) ;
Contoh soal • Buatlah program untuk menampung data mhs di suatu file teks. Data mhs dibuat dalam bentuk struct yang terdiri dari: – Roll (kelas) – Dept_code (NIM) – GPA (IP)
Contoh soal • Suatu file teks berisi data mahasiswa yang merupakan suatu struktur data yang berisi: – Roll (kelas) – Dept_code (NIM) – GPA (IP) Buatlah program untuk menghitung IP rerata dari data-data yang ada di file tsb!
Jawab typedef struct { int roll; char dept_code[6]; float cgpa; } STUD; main() { FILE *stud; STUD s; float sum = 0. 0; int count = 0; stud = fopen (“stud. dat”, “r”) ; while (1) { if (feof (stud)) break; fscanf (stud, “%d %s %f”, &s. roll, s. dept_code, &s. cgpa); count ++; sum += s. cgpa; } printf (“n. The average cgpa is %f”, sum/count); fclose (stud); }
Binary File • Binary files can not be created by an editor (as with text files) • A binary file is created by writing on it from a C-program
Binary file fopen modes • • • “rb” : open binary file for read “wb” : create binary file for write “ab” : append to a binary file “r+b” : open binary file for read/write “w+b” : create binary file for read/write “a+b” : append to or create a binary file for read/write
example • Membuat suatu file biner untuk menampung array bilangan integer kemudian membacanya FILE *binaryp, *inbinp; int i, list[255]; binaryp = fopen("nums. bin", "wb"); //create file nums. bin for (i = 2; i <= 500; i += 2) fwrite(&i, sizeof (int), 1, binaryp); fclose(binaryp); /* read 250 integers into a vector */ inbinp = fopen(”nums. bin”, ”rb”); //buka file nums. bin fread(list, sizeof(int), 250, inbinp); fclose(inbinp);
- Slides: 26