使用系统调用来实现unix cat命令
发布时间:2020-12-15 22:20:52 所属栏目:安全 来源:网络整理
导读:对于我的OS类,我负责使用系统调用实现Unix的cat命令(没有scanf或printf).这是我到目前为止所得到的: (编辑感谢回复) #include sys/types.h#include unistd.h#include fcntl.h#include stdio.h#include stdlib.h#include string.h#include math.hmain(void){
对于我的OS类,我负责使用系统调用实现Unix的cat命令(没有scanf或printf).这是我到目前为止所得到的:
(编辑感谢回复) #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> main(void) { int fd1; int fd2; char *buffer1; buffer1 = (char *) calloc(100,sizeof(char)); char *buffer2; buffer2 = (char *)calloc(100,sizeof(char)); fd1 = open("input.in",O_RDONLY); fd2 = open("input2.in",O_RDONLY); while(eof1){ //<-lseek condition to add here read (fd1,buffer1,/*how much to read here?*/ ); write(1,sizeof(buffer1)-1); } while (eof2){ read (fd2,buffer2,/*how much to read here?*/); write(1,sizeof(buffer2)-1); } } 我见过的例子只显示了已知字节数的读数.我不知道每个读取文件有多少字节,所以如何指定读取的最后一个参数? 解决方法
>在您读入缓冲区之前,您必须分配一个缓冲区.在堆栈上(最简单)或使用mmap.
> perror是一个复杂的库函数,而不是系统调用. > exit不是Linux上的系统调用.但_exit是. >不要写更多的字节而不是之前读过的字节. >或者,通常:阅读所有这些系统调用的文档. 编辑:这是我的代码,只使用系统调用.错误处理有些限制,因为我不想重新实现perror. #include <fcntl.h> #include <unistd.h> static int cat_fd(int fd) { char buf[4096]; ssize_t nread; while ((nread = read(fd,buf,sizeof buf)) > 0) { ssize_t ntotalwritten = 0; while (ntotalwritten < nread) { ssize_t nwritten = write(STDOUT_FILENO,buf + ntotalwritten,nread - ntotalwritten); if (nwritten < 1) return -1; ntotalwritten += nwritten; } } return nread == 0 ? 0 : -1; } static int cat(const char *fname) { int fd,success; if ((fd = open(fname,O_RDONLY)) == -1) return -1; success = cat_fd(fd); if (close(fd) != 0) return -1; return success; } int main(int argc,char **argv) { int i; if (argc == 1) { if (cat_fd(STDIN_FILENO) != 0) goto error; } else { for (i = 1; i < argc; i++) { if (cat(argv[i]) != 0) goto error; } } return 0; error: write(STDOUT_FILENO,"errorn",6); return 1; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |