标签:文件夹 directory waitpid put quit fun white open 返回
第一章 基础知识
目录 文件 路径
#include "ourhdr.h"
#include <sys/types.h>
#include <dirent.h>
//查找文件夹内容
int main(int argc,char** argv)
{
DIR *dp; //指向文件的指针 typedef struct __dirstream DIR;
struct dirent *dirp;
if(argc !=2)
err_quit("a single argument (the directory"); //出错提示
if((dp = opendir(argv[1])) ==NULL) //opendir 返回指向dir结构体的指针
err_sys("can‘t open %s",argv[1]);
while((dirp = readdir(dp))!=NULL) //循环调用readdir
{
printf("%s\n",dirp->d_name);
//
}
printf("%s\n",dirp->d_type);
closedir(dp); //关闭文件
exit(0);
return 0;
}
不用缓存的IO
函数: open read write lseek close
#include "ourhdr.h"
#define BUFFERSIZE 8192
int main(void)
{
int n;
char buf[BUFFERSIZE];
while((n=read(STDIN_FILENO,buf,BUFFERSIZE))) //从总端读取字符
if(write(STDIN_FILENO,buf,n)!=n) //把字符写入终端
err_sys("write error");
if(n<0)
err_sys("read error");
exit(0);
}
#include "ourhdr.h"
int main(void)
{
int c;
while((c=getc(stdin))!=EOF)//读取一个字节
if(putc(c,stdout)==EOF)
err_sys("output error");
if(ferror(stdin))
err_sys("input error");
putc(EOF,stdout); //END OF FILE
exit(0);
}
进程控制的主要函数: fork exec waitpid
#include "ourhdr.h"
int main(void)
{
char buf[MAXSIZE];
pid_t pid;
int status;
printf("%% ");
while(fgets(buf,MAXSIZE,stdin)!=NULL) //从终端读入字符
{
buf[strlen(buf)-1] = 0;//
if((pid=fork())<0)
err_sys("fork error");
else if(pid ==0 )
{
execlp(buf,buf,(char*)0); //执行buf
err_ret("could‘t execte :%s ",buf);
exit(127);
}
if((pid = waitpid(pid,&status,0))<0)
err_sys("waitpid error");
printf("%% ");
}
exit(0);
}
#include "ourhdr.h"
int main(int argc,char** argv)
{
fprintf(stderr,"EACCES:%s\n",strerror(EACCES));
errno = ENOENT;
perror(argv[0]);
exit(0);
}
#include "ourhdr.h"
static void sig_int(int); //our signal-catching function
int main(void)
{
char buf[MAXLINE];
pid_t pid;
int status;
if(signal(SIGINT,sig_int) == SIG_ERR) //参数1 要处理的信号 参数2 处理方式
err_sys("signal error");
printf("%% ");
while(fgets(buf,MAXLINE,stdin)!=NULL)
{
buf[strlen(buf)-1]=0;
if((pid = fork())<0)
err_sys("fork error");
else if (pid ==0)
{
execlp(buf,buf,(char*)0);
err_ret("couldn‘t execute: %s",buf);
exit(127);
}
if((pid = waitpid(pid,&status,0))<0)
err_sys("waitpid error");
printf("%% ");
}
exit(0);
}
void sig_int(int signo)
{
printf("interrupt \n%%");
}
标签:文件夹 directory waitpid put quit fun white open 返回
原文地址:https://www.cnblogs.com/countryboy666/p/10922001.html