Professional Documents
Culture Documents
ตอนที่ 1
จงเขียนโปรแกรมโดยใช้ ANSI C และทำำงำนบน Solaris Unix เพือ
่
จำำลองกำรทำำงำนของคำำสัง่ UNIX ดังต่อไปนี ้
ผลการทดลองคำาสัง่ ls
1. ทฤษฎีและวิธีกำรออกแบบ
โปรแกรมใช้กำรรับค่ำจำกค่ำทีป
่ ้ อนเข้ำไป โดยกำรประกำศตัวแปร
เป็ น Array Of Character ทีม
่ ีชือ
่ ของคำำสัง่ อย่่แล้วคือ ls,ls –l,ls –la
และเพิม
่ คำำสัง่ สำำหรับออกจำกโปรแกรมด้วย exit
กำรทำำงำนคือ รับค่ำจำก keyboard มำเก็บไว้ในตัวแปร Input แล้ว
นำำค่ำมำเปรียบเทียบกับ ตัวแปร data ทีไ่ ด้ตัง้ ไว้เหมือนกันหรือไม่โดย
ใช้ strcmp (String Compare)เปรียบเทียบ โดยจะต้องประกำศ
#include<stdlib.h> ประกำศเพือ
่ ใช้คำำสัง่ system
#include<string.h> ประกำศเพือ
่ ใช้คำำสัง่ strcmp
ถ้ำค่ำเหมือนกันจะได้ 0 ตรงกับเงือ
่ นไข ให้ทำำคำำสัง่ system ซึง่ ขึน
้ อย่่
กับคำำสัง่ แต่ละคำำสัง่ เช่น พิมพ์ ls ก็จะทำำคำำสัง่ ls
ถ้ำต้องกำรออกจำกโปรแกรมให้พิมพ์ exit แต่ถ้ำพิมพ์คำำสัง่ ผิด โปรแกรม
จะแจ้งว่ำ
Not command found แล้วขึน
้ => (เป็ นสัญลักษณ์ command promt) เพือ
่
ให้พิมพ์คำำสัง่ ใหม่
2. Input program screen
คำำสัง่ ls
คำำสัง่ ls -l
คำำสัง่ ls -la
เมือ
่ พิมพ์คำำสัง่ ผิด โปรแกรมจะแสดงข้อควำม error
ผลการทดลองคำาสัง่ cp
1. ทฤษฏีและวิธีกำรออกแบบ
ในตอนแรกจะมีกำรรับค่ำโดยใช้คำำสัง่
Cp ชือ
่ ไฟล์ ชือ
่ ไฟล์ที ่ copy หรือ ตำำแหน่งปลำยทำง
ใช้กำรรับค่ำ 2 ค่ำ จำก คีย์บอร์ด เป็ น char เก็บไว้ใน สตริง
ใช้กำร fopen คือกำรเปิ ดไฟล์ “r” เปิ ดอ่ำนอย่ำงเดียว แล้ว เขียนเป็ นไฟล์
ใหม่ โดยใช้ fopen “w+”
แล้วใช้ if เช็คไฟล์ ต้นทำง แล้วใช้คำำสัง่ while วน loop โดยใช้ gets ไฟล์
ต้นฉบับ ทีละ 49 ตัวอักษร 50 สตริง
และใช้ puts ไฟล์ปลำยทำง เมือ
่ เสร็จแล้วก็จะใช้คำำสัง่ fclose และ แสดงผล
Copy Complete
2. Input program screen
สร้ำงไฟล์ test.txt ขึน
้ มำเพือ
่ ใช้ในกำรทดสอบโปรแกรม
รันโปรแกรม ชือ
่ copy ที ่ cpmpile เสร้จแล้ว และใช้คำำสัง่ cp เพือ
่ copy
ไฟล์ test.txt ไปเป็ น test2.txt
จำกนัน
้ เข้ำไปทีโ่ ฟลเดอร์ test_folder ว่ำมีไฟล์ทถ
ี ่ ่กย้ำยไว้หรือไม่
#include <fcntl.h>
#include <unistd.h>
main(){
int fd;
ssize_t nread;
char buf[1024];
if (fd == -1){
perror(“Error in read data”);
exit(1);
}
ผลการทดลองตอนที่ 2
1. เขียน code ทีใ่ ห้มำ ตัง้ ชือ
่ เป็ น read.c
2. คอมไพล์ ใช้คำำสัง่ gcc read.c –o read
3. รันไฟล์ exe
4. เช็คเอำท์พุต
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
main(){
int fd;
char *filename = "wfile";
char *content = "Hello World!";
if (fd == -1){
printf("Couldn't create %s\n", filename);
exit(1); /* error, so exit */
}
exit(0);
}
8. Use vi to open it or use cat to list out the file content. What
is the file content?
3. Standard input, standard output and standard error
/* Filename: io.c */
#include <stdlib.h>
#include <unistd.h>
main(){
ssize_t nread;
char buf[SIZE];
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
main(){
int fd;
ssize_t nread;
char buf[1024];
if (fd == -1){
fprintf(stderr, “File data not found\n”);
exit(1);
}
Revision Exercise
เช่น
progname 37 15
จะได้
argc = 3
argv[0] = "progname"
argv[1] = "37"
argv[2] = "15"