file handling

Download File Handling

Post on 24-Feb-2016

57 views

Category:

Documents

0 download

Embed Size (px)

DESCRIPTION

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: - PowerPoint PPT Presentation

TRANSCRIPT

  • File Handling

  • Pemrograman FileMembuat suatu file baruMembuka suatu fileMenutup suatu fileMembaca suatu fileMenutup suatu file

  • Lingkup fileSecara umum pada C, semua piranti komputer bisa dianggap sebagai fileLingkup file yang akan dibahas pada materi ini:Kumpulan data yang disimpan pada media penyimpan (disk)

  • Text & Binary FileText file hanya berisi teks, terdiri dari karakter-karakter ascii, tanpa ada formatting. Contoh: file teks(dibuat pakai notepad), file source codeBinary 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:File yg tersimpandi disklinkPointer to File :AlokasiMemori komputerUtk memprosesfileProses open file:Membuat link antaraFile dgn pointer to fileDISKMEMORIProses close file:Memutus link file - pointer

  • File handling in CIn 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 */}

  • Opening a FileA 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 onlya :: open the file for appending data to it

  • Fungsi fopenBerfungsi 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 sajaJika namafile belum ada, maka komputer akan membuat (create) file tersebut dahulu

  • Modes for opening text filesThe 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 modesr+ : open text file for read/writew+ : create text file for read/writea+ : append to or create a text file for read/write

  • Gambaran efek masing2 mode pada suatu file teksabcdefghiSebelum fopenSetelah fopen(ada isinya)(kosong)w,w+abcdefghiSebelum fopenSetelah fopenr,r+abcdefghiPointer fileAda disiniabcdefghiSebelum fopenSetelah fopena,a+abcdefghi Pointer fileAda disini

  • Closing a FileAfter 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 fprintffprintf 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);

  • PercobaanBuat sembarang file teks dengan notepad dan namai file tsb dengan nama file.datIsilah file tsb dengan sembarang karakter misalnya abcbdefBuatlah program seperti pada slide sebelumnyaLetakkan file teks tsb satu folder dengan programEksekusi 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 fgetsfgets is a better way to read from a fileWe can read into a string using fgetsFILE *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 maximumnumber of characters to read and a file pointer.It returns NULL if there is an error (such as EOF)

  • fscanf and fprintfWe 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) ;

  • Other Read/Write Operations on FilesThe 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 soalBuatlah program untuk meng-convert huruf-huruf pada suatu text file menjadi uppercase!

  • Example :: convert a text file to all UPPERCASEmain() { 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 soalBuatlah 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)

  • Contoh soalSuatu 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!

  • Jawabtypedef 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);}

  • Binary FileBinary 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 readwb : create binary file for writeab : append to a binary filer+b : open binary file for read/writew+b : create binary file for read/writea+b : append to or create a binary file for read/write

  • exampleMembuat suatu file biner untuk menampung array bilangan integer kemudian membacanyaFILE *binaryp, *inbinp;int i, list[255];binaryp = fopen("nums.bin", "wb");//create file nums.binfor (i = 2; i