Download - File Handling

Transcript
Page 1: File Handling

File Handling

Page 2: File Handling

Pemrograman File

• Membuat suatu file baru• Membuka suatu file• Menutup suatu file• Membaca suatu file• Menutup suatu file

Page 3: File Handling

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)

Page 4: File Handling

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

Page 5: File Handling

Bagaimana kita memperlakukan file di C:

File yg tersimpandi disk

link Pointer to File :Alokasi

Memori komputerUtk memproses

file

Proses open file:Membuat link antaraFile dgn pointer to fileDISK MEMORI

Proses close file:Memutus link file - pointer

Page 6: File Handling

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 */}

Page 7: File Handling

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

Page 8: File Handling

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

Page 9: File Handling

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

Page 10: File Handling

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

Page 11: File Handling

Gambaran efek masing2 mode pada suatu file teks

abcdefghi

Sebelum fopen Setelah fopen

(ada isinya) (kosong)

w,w+

abcdefghi

Sebelum fopen Setelah fopen

r,r+ abcdefghi

Pointer fileAda disini

abcdefghi

Sebelum fopen Setelah fopen

a,a+ abcdefghi

Pointer fileAda disini

Page 12: File Handling

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

Page 13: File Handling

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

Page 14: File Handling

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

Page 15: File Handling

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 maximumnumber of characters to read and a file pointer.It returns NULL if there is an error (such as EOF)

Page 16: File Handling

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

Page 17: File Handling

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

Page 18: File Handling

Contoh soal

• Buatlah program untuk meng-convert huruf-huruf pada suatu text file menjadi uppercase!

Page 19: File Handling

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

Page 20: File Handling

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

Page 21: File Handling

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)

Page 22: File Handling

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!

Page 23: File Handling

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

Page 24: File Handling

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

Page 25: File Handling

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

Page 26: File Handling

example• Membuat 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 <= 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.binfread(list, sizeof(int), 250, inbinp);fclose(inbinp);