終於開始看 The C 的第八章 The UNIX System Interface 了!這是比較激動人心的一章,學過之後就可以開始寫 Unix 程式了,比如列印目錄,查看檔案大小、檔案屬性等,也就是說可以寫一些比較實用的小程式了。而且一些系統函數,例如 read(),write()等,是 unix 編程的基礎。另外,也講解了 malloc 的一種實現方法,我想這將會加深我對記憶體的理解。
然而,第一個例子就讓我傻眼了。
#include "syscalls.h"
main()
{
char buf[BUFSIZ];
int n;
while ((n = read(0, buf, BUFSIZ)) > 0)
write(1, buf, n);
return 0;
}
編譯時間出錯
k@bian:~$ gcc -Wall test.c
test.c:1:22: syscalls.h: No such file or directory
test.c:5: error: `BUFSIZ' undeclared (first use in this function)
test.c:8: warning: implicit declaration of function `read'
test.c:9: warning: implicit declaration of function `write'
書上說 read()和write(),還有BUFSIZ都是 syscalls.h 裡定義的。
我開啟 /usr/include/ 一看,沒有syscalls.h !不過有一個 syscall.h,換上這個還是提示錯誤。
Linux畢竟不是Unix,我當時就有點害怕這一章學不下去。這種時候,當然要google!
沒有直接查到解決辦法,卻知道了可以用man來查
man read
哈哈,有了!赫然寫著
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
但是還有問題
k@bian:~$ gcc -Wall test.c
test.c:5: error: `BUFSIZ' undeclared (first use in this function)
這時我突然想到一個辦法,用 grep !
k@bian:~$ grep BUFSIZ /usr/include/*
/usr/include/_G_config.h:#define _G_BUFSIZ 8192
/usr/include/libio.h:#define _IO_BUFSIZ _G_BUFSIZ
/usr/include/stdio.h:#ifndef BUFSIZ
/usr/include/stdio.h:# define BUFSIZ _IO_BUFSIZ
/usr/include/stdio.h: Else make it use buffer BUF, of size BUFSIZ. */
原來在stdio.h裡!
程式改成這樣,問題解決
#include <stdio.h>
#include <unistd.h>
main()
{
char buf[BUFSIZ];
int n;
while ((n = read(0, buf, BUFSIZ)) > 0)
write(1, buf, n);
return 0;
}
好!可以往下學了:D
還找到這個,在Linux下編程肯定有用的 The GNU C Library Manual。有幾種格式提供下載,建議下載formatted in HTML (976K gzipped tar file) with one web page per node.