1 / 26

File Handling

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:

arne
Download Presentation

File Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. File Handling

  2. Pemrograman File • Membuat suatu file baru • Membuka suatu file • Menutup suatu file • Membaca suatu file • Menutup suatu file

  3. 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)

  4. 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

  5. Bagaimana kita memperlakukan file di C: Proses open file: Membuat link antara File dgn pointer to file File yg tersimpan di disk Pointer to File : Alokasi Memori komputer Utk memproses file MEMORI DISK link Proses close file: Memutus link file - pointer

  6. 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[]= "file2.dat"; fptr= fopen (filename,"w"); if (fptr == NULL) { fprintf (stderr, “ERROR”); /* DO SOMETHING */ }

  7. 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

  8. 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

  9. 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

  10. 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

  11. Gambaran efek masing2 mode pada suatu file teks Sebelum fopen Setelah fopen Sebelum fopen Setelah fopen abcdefghi abcdefghi abcdefghi w,w+ a,a+ (ada isinya) (kosong) Pointer file Ada disini Sebelum fopen Setelah fopen abcdefghi abcdefghi r,r+ Pointer file Ada disini

  12. 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) ;

  13. 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);

  14. 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

  15. 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 %s\n",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)

  16. 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, “\nThe result is: %d”, xyz) ;

  17. 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) ;

  18. Contoh soal • Buatlah program untuk meng-convert huruf-huruf pada suatu text file menjadi uppercase!

  19. 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) ; }

  20. 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”) ;

  21. Contoh soal • Buatlah program untuk menampung data-data mhs di suatu file teks. Data mhs dibuat dalam bentuk struct yang terdiri dari: • Roll (kelas) • Dept_code (NIM) • GPA (IP)

  22. 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!

  23. 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 (“\nThe average cgpa is %f”, sum/count); fclose (stud); }

  24. 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

  25. 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

  26. 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);

More Related