计算缓存区大小
#include<stdio.h>
int main()
{
printf("hello\n");//系统调用,开辟缓冲区,刷新后缓存区为空
int a=stdout->_IO_buf_end-_IO_buf_base;//stdout指向终端文件,计算系统调用时产生的缓存区大小
printf("%d\n",a);
return 0;
}
实现cat功能
#include<stdio.h>
int main()
{
FILE *fp;
fp=fopen(argv[1],"r");
if(fp==NULL)
{
printf("open error\n");
return -1;
}
char ch;
while(ch=fgetc(fp)!=EOF)
{
printf("%c",ch);
ch=fgetc(fp);
}
}
实现wc -l功能
#include<stdio.h>
#include<string.h>
int main()
{
FILE *fp;
fp=fopen("1.c","r");
if(fp==NULL)
{
printf("open error\n");
return -1;
}
//1.
char buf[32]="";
int a=0;
while(fgets(buf,32,fp)!=NULL)
{
if((buf[strlen(buf)-1])=='\n')
a++;
}
printf("%d\n",a);
//2.
char ch;
ing a=0;
while((ch=fgetc(fp))!=NULL)
{
if(ch=='\n')
a++;
}
printf("%d",a);
return 0;
}
实现head -n功能
#include<stdio.h>
int main()
{
char buf[32]="";
int n=0,line;
if(argr!=3)
{
printf("Usage:%s <-n> <file>\n",argv[0]);
return -1;
}
FILE *fp;
fp=fopen(argv[2],"r");
if(fp==NULL)
{
printf("open error\n");
return -1;
}
line=atoi(argv[1]+1);
while(fgets(buf,32,fp)!=NULL)
{
if((buf[strlen(buf)]-1)=='\n')
n++;
printf("%s",buf);
if(n==line)
break;
}
fclose(fp);
return 0;
}