#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>

/* 
 * I guess this is the hard way of solving problem 5
 * Not sure if they particularly wanted it like this
 * the nuber of .h files can certainly be reduced
 */
	
int main()
{	
	char *file="text";
	char tmp_file[20];		/*temporary storage for the filename */
	int open_ret, i,j;	/* Return values variables and counter */

	/* 
	 * Start at 3 since 0-2 are already open
	 */
	for(i=3,j=1;;i++,j++)
	{		
			/*
			 * Copy the base name and concatenate the number to it
			 * open the file and reset the filename
			 */	
			sprintf(tmp_file, "%s_%d", file, j);
			open_ret=open(tmp_file, O_CREAT, 00644);
			strcpy(tmp_file, "\0");
			
			/* Stop if state of :Too many files open is reached */
			if(open_ret==-1) break;
	}

	/* Print the result */
	printf("number of possible open fd: %d \n", i);
	
	/*
	 * erase all files created
	 * same procedure as above
	 */
	for(i=3,j=1;;i++,j++)
	{	
		sprintf(tmp_file, "%s_%d", file, j);
		if(unlink(tmp_file)==-1) break;
	}
		
	return(0);
}	

/*
##### OUTPUT #####

adimitro@alef:/student/adimitro/cwork> ./a.out
number of possible open fd: 256
adimitro@alef:/student/adimitro/cwork>
*/
