您的位置:首页 > 运维架构 > Linux

用c语言程序实现系统的cp命令 在linux下调用syscalls.h头文件

2012-08-17 17:18 971 查看
所以用C实现的步骤是:

1、解析命令,就是提取出源路径和目标路径,以及文件名

2、写一个切换目录的函数,比如chgdir(char *),路径名字做参数。

3、执行切换目录函数,正确执行后,在这个目录下找到目标文件,定义一个缓冲区,把文件内容拷贝进去,找不到文件另作处理。

4、再调用2步骤中的目录切换函数,在目标路径下建立一个空文件并把缓冲区内容写进去,保存。

在linux下调用syscalls.h头文件

终于开始看 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;

}

编译时出错

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

但是还有问题

gcc -Wall test.c

test.c:5: error: `BUFSIZ' undeclared (first use in this function)

这时我突然想到一个办法,用 grep !

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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: