IO day3(opendir/readdir/closedir)

#include
#include
#include
#include
#include
#include
#include
#include

#define MAX 32

int main(int argc, const char *argv[])
{
	DIR *dp=opendir("./");
	if(dp==NULL)
	{
		perror("opendir");
		return -1;
	}
	struct dirent *rp=NULL;
	int count=1;
	while(1)
	{
		rp=readdir(dp);
		if(NULL==rp)
		{
			if(errno==0)
			{
				printf("end\n");
				break;
			}
			else
			{
				perror("readdir");
				return -1;
			}
		}
		if(rp->d_name[0]!='.')
		{
			printf("[%2d] %s\n",count,rp->d_name);
			count++;
		}

	}
	if(closedir(dp))
	{
		perror("closedir");
		return -1;

	}

	int a;
	printf("你要查看第几个文件:");
	scanf("%d",&a);
	DIR *pp=opendir("../day3/");
	rp=NULL;
	count=0;
	char arr[20]="";
	while(a!=count)
	{
		rp=readdir(pp);
		if(NULL==rp)
		{
			if(errno==0)
			{	

				printf("over\n");
				break;
			}
			else
			{
				perror("readdir");
				return -1;
			}
		}
		if(rp->d_name[0]!='.')
		{
			//	printf("[%d] %s\n",count,rp->d_name);
			count++;
		}
	}
	char s[MAX]="";
	strcat(s,rp->d_name);
	int fp=open(s,O_RDONLY);
	if(fp<0)
	{
		perror("open");
		return -1;
	}

	bzero(arr,sizeof(arr));
	ssize_t res=0;
	while(1)
	{
		bzero(arr,sizeof(arr));
		res=read(fp,arr,sizeof(arr));
		if(0==res)
		{
			break;
		}
		write(1,arr,res);
	}

	if(close(fp)<0)
	{
		perror("close");
		return -1;
	}


	if(closedir(pp))
	{
		perror("closedir");
		return -1;

	}
	printf("success\n");
	return 0;
}

你可能感兴趣的:(IO,算法,c++,数据结构)