130 likes | 204 Views
การทำงานกับ Files. ธวัชชัย เอี่ยมไพโรจน์. UNIX File Structure. ดูรายละเอียดได้ที่ http://lecture.compsci.buu.ac.th/~f44404/doc/file.ppt บน UNIX ทุกๆ อย่างเป็น File ตั้งแต่ disk files, serial ports, printers และอุปกรณ์อื่นๆ สามารถใช้ basic functions ต่อไปนี้จัดการได้หมด
E N D
การทำงานกับ Files ธวัชชัย เอี่ยมไพโรจน์
UNIX File Structure • ดูรายละเอียดได้ที่ http://lecture.compsci.buu.ac.th/~f44404/doc/file.ppt • บน UNIX ทุกๆ อย่างเป็น File ตั้งแต่ disk files, serial ports, printers และอุปกรณ์อื่นๆ • สามารถใช้ basic functions ต่อไปนี้จัดการได้หมด open, close, read, write, ioctl
คำสั่งที่ควรศึกษา • od -c <filename> • od -d <filename> • คำถาม คำสั่งทั้ง 2 ทำอะไรกับ File • inode คืออะไร ?
Files / Devices • /dev/console • /dev/tty • /dev/null • system calls : เป็นบริการจาก UNIX และติดต่อโดยตรงกับ OS • device drivers: เป็น low level interfaces สำหรับควบคุม Hardware
System called สำหรับ device drivers • Open a file or device. : open • Read from an open file or device. : read • Write to a file or device. : write • Close the file or device. : close • Specific control the device. : ioctl ioctl( ) ของแต่ละเครื่องอาจแตกต่างกันได้
ประสิทธิภาพ • UNIX ต้อง switch จากโปรแกรม แล้วไป run kernel code แล้วต้อง switch กลับมาอีก • Hardware limit เกี่ยวกับขนาดของ data blocks ซึ่ง low level function call สามารถใช้ได้มีขนาดจำกัด • นิยมใช้ Library Functions เช่น stdio.h แทน • แต่ยังมีที่จำเป็นต้องใช้อีกมาก
Low-level File Access • 0 : standard input 1: standard output 2 : standard error • write ดูโปรแกรมตัวอย่างที่ http://lecture.compsci.buu.ac.th/~f44213/samples/jun26/write.c • read ดูโปรแกรมตัวอย่างที่ http://lecture.compsci.buu.ac.th/~f44213/samples/jun26/read.c • open • close • ioctl
A File Copy Program • ศึกษาได้จาก http://lecture.compsci.buu.ac.th/~f44213/samples/jun26/system.c
lseek • เป็น low level system call ในการหาตำแหน่งใน file SEEK_SET SEEK_CUR SEEK_END • man lseek
get file status system call • stat : fstat : lstat struct stat { dev_t st_dev; /* device */ ino_t st_ino; /* inode */ ….. }; เป็น structure ที่ต้องศึกษาให้เข้าใจ
dup และ dup2 • duplicate a file descriptor #include <unistd.h> int dup(int oldfd); int dup2(int oldfd, int newfd);
File Maintenance (man 2 <fname>) • chmod int chmod(const char *path, mode_t mode); • chown int chown(const char *path, uid_t owner, gid_t group); • link int link(const char *oldpath, const char *newpath); • unlink int unlink(const char *pathname);
Directories Maintenance (man 2 <fname>) • mkdir int mkdir(const char *pathname, mode_t mode); • rmdir int rmdir(const char *pathname); • chdir int chdir(const char *path); • getcwd [man getcwd] char *getcwd(char *buf, size_t size);