您的位置:首页 > 编程语言

cat命令的具体实现代码

2013-06-21 22:13 176 查看
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

#define BUFFERSIZE 4096

int main(int argc, char *argv[])
{
int fd, fd_tty, n_chars;
char buf[BUFFERSIZE];

if (argc != 2)
{
fprintf(stderr, "Usage: %s filename\n", *argv);
exit(1);
}

if ((fd = open(argv[1], O_RDONLY)) == -1)
{
perror("Open error!");
exit(1);
}

/* /dev/tty 表示输入终端 */
if (fd_tty = open("/dev/tty", O_RDWR) == -1)
{
perror("Open error!");
exit(1);
}

while ((n_chars = read(fd, buf, BUFFERSIZE)) > 0)
{
if (write(fd_tty, buf, n_chars) != n_chars)
{
perror("Write error!");
exit(1);
}
}

if (close(fd) == -1)
perror("Error closing files!");

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: