int main(int argc, char* argv[]) {	
	DynArr* b;
	int n, i;
	double t1, t2;

	for(n=1000; n < 200000; n=n*2) /* outer loop */
	{

	  
	b = createDynArr(n); 
		
	for( i = 0 ; i < n; i++) {
		addDynArr(b, (TYPE)i); /*Add elements*/
	}		
	
	t1 = getMilliseconds();/*Time before contains()*/
	
	for(i=0; i<n; i++) {
		containsDynArr(b, i);		
	}	
	
	t2 = getMilliseconds();/*Time after contains()*/
	
	printf("Time for running contains() on %d elements: %g ms\n", n, t2-t1);
  
	/* delete DynArr */
	deleteDynArr(b);
 	}	
	return 0;
}
Example #2
0
/*  Delete the list

    param:  heap    pointer to the list
    post:   The tasks from the list are removed and their occupied memories are freed

*/
void deleteList(DynArr *heap)
{

	Task* task;
	while(sizeDynArr(heap) > 0)
	{
	  	/* get the task */
		task = getMinHeap(heap);
		/* remove the task */
		removeMinHeap(heap);
		/* free the task */
		free(task);
	}
	/* free the heap */
	deleteDynArr(heap);
}
Example #3
0
/* Checks whether the parentheses are balanced or not
	param: 	s pointer to a string
	pre: s is not null
	post:
*/
int isBalanced(char* s)
{
    struct DynArr *array = newDynArr(10);
    char c;
    while((c = nextChar(s)) != '0'){
        switch(c){
            case '{' :
            case '[' :
            case '(' :
                pushDynArr(array, c);
                break;

            case '}' :
                if(topDynArr(array) == '{'){
                    popDynArr(array);
                    break;
                }
                return 0;

            case ']' :
                if(topDynArr(array) == '['){
                    popDynArr(array);
                    break;
                }
                return 0;

            case ')' :
                if(topDynArr(array) == '('){
                    popDynArr(array);
                    break;
                }
                return 0;

        }
    }
    if(array->size != 0){
        return 0;
    }
    deleteDynArr(array);
        return 1;

}
int main(int argc, char* argv[]) {	
	DynArr* b;
	int n, i;
	double t1, t2;
	#ifdef MEMORY_TEST_INCLUDED
	/* variables to hold memory used before and after creating DynArr */	
	long m1, m2;
	/* memory used BEFORE creating DynArr */
	m1 = getMemoryUsage();
	#endif

	if( argc != 2 ) return 0;
	  
	b = createDynArr(1000); 
	n = atoi(argv[1]); /*number of elements to add*/
		
	for( i = 0 ; i < n; i++) {
		addDynArr(b, (TYPE)i); /*Add elements*/
	}		
	
	#ifdef MEMORY_TEST_INCLUDED
	/* memory used AFTER creating DynArr */
	m2 = getMemoryUsage();  
	printf("Memory used by DynArr: %ld KB \n", m2-m1);
	#endif
	
	t1 = getMilliseconds();/*Time before contains()*/
	
	for(i=0; i<n; i++) {
		containsDynArr(b, i);		
	}	
	
	t2 = getMilliseconds();/*Time after contains()*/
	
	printf("Time for running contains() on %d elements: %g ms\n", n, t2-t1);
  
	/* delete DynArr */
	deleteDynArr(b);
	
	return 0;
}
int main(int argc, char* argv[])
{
	#ifdef MEMORY_TEST_INCLUDED
	// Memory used BEFORE creating LinkedList
	long m1 = getMemoryUsage();
	#endif

	if (argc != 2)
	{
		printf("Usage: %s <number of elements to add>\n", argv[0]);
		return 1;
	}
	
	DynArr *a = newDynArr(1024);
	
	int numElements = atoi(argv[1]);
	int i;
	for (i = 0 ; i < numElements; i++)
	{
		addDynArr(a, (TYPE)i);
	}

	#ifdef MEMORY_TEST_INCLUDED
	// Memory used AFTER creating LinkedList
	long m2 = getMemoryUsage();
	printf("Memory used by Dynamic Array : %ld KB \n", m2 - m1);
	#endif

	double t1 = getMilliseconds(); // Time before contains()
	for (i = 0; i < numElements; i++)
	{
		containsDynArr(a, i);
	}
	double t2 = getMilliseconds(); // Time after contains()
	printf("Time for running contains() on %d elements: %g ms\n", numElements, t2 - t1);

	deleteDynArr(a);

	return 0;
}
Example #6
0
/*  Print the list
 
 param:  heap    pointer to the list
 pre:    the list is not empty
 post:   The tasks from the list are printed out in priority order.
 The tasks are not removed from the list.
 */
void printList(DynArr *heap)
{
    DynArr *temp;
    TaskP task;
    assert(sizeDynArr(heap) > 0);
    
    temp = createDynArr(sizeDynArr(heap));
    /* copy the main list to a temp list
     * so that tasks can be printed out and removed.
     */
    copyDynArr(heap, temp);
    while(sizeDynArr(temp) > 0)
    {
        /* get the task */
        task = getMinHeap(temp);
        /* print the task */
        printf("%d:  %s\n\n", task->priority, task->description);
        /* remove the task */
        removeMinHeap(temp);
    }
    /* free the temp list */
    deleteDynArr(temp);
}
/* Resizes the underlying array to be the size cap

	param: 	v		pointer to the dynamic array
	param:	cap		the new desired capacity
	pre:	v is not null
	post:	v has capacity newCap
*/
void _dynArrSetCapacity(DynArr *v, int newCap)
{
	/* FIXME: You will write this function */
	assert(v!= 0);
	struct DynArr *newArr = createDynArr(newCap);
	int newSize = sizeDynArr(v); //same as v so all the data can transfer

	int i;
	for (i = 0; i<newSize; i++) {
        newArr->data[i] = v->data[i]; //transfer data from v to newArr
	}

	freeDynArr(v);
    v->capacity = newCap; //new capacity set for v
    v->size = newSize;
	v->data = malloc(sizeof(DynArr)*newCap); //v created with a new "size" aka capacity

	for (i = 0; i<newSize; i++) {
        v->data[i] = newArr->data[i]; //transfer data back into v with new capacity
	}

	deleteDynArr(newArr); //no longer needed
}
Example #8
0
/*  Print the list in priority order.  This requires that either we sort it...or make a copy and pull
off the smallest element one at a time.  That's what we've done here.

    param:  heap    pointer to the list
    pre:    the list is not empty
    post:   The tasks from the list are printed out in priority order.
			The tasks are not removed from the list.
*/
void printList(DynArr *heap)
{
  DynArr *temp;
  TaskP task;
  assert(sizeDynArr(heap) > 0);

  temp = createDynArr(sizeDynArr(heap));
  /* copy the main list to a temp list
   * so that tasks can be printed out and removed.
   */
  copyDynArr(heap, temp);
  while(sizeDynArr(temp) > 0)
    {
      /* get the task */
      task = getMinHeap(temp);

      /* print the task */
      printf("%d:  %s\n\n", task->priority, task->description);
      /* remove the task , but let's not free up the memory it's pointing to since old Arr is using it!*/
      removeMinHeap(temp, compare);
    }
  /* free the temp list */
  deleteDynArr(temp);
}
Example #9
0
/* Checks whether the (), {}, and [] are balanced or not
	param: 	s pointer to a string 	
	pre: s is not null	
	post:	
*/
int isBalanced(char* s)
{
	char c = ' ';
	int ret_val = 0;
	struct DynArr* stack = newDynArr(10);
	assert(stack != 0);
	assert(s != 0);
	while (c != '\0'){
		ret_val = 1;
		c = nextChar(s);

		if (c == '(' || c == '[' || c == '{') pushDynArr(stack,c);
		if (c == ')' || c == ']' || c == '}') {
			if (c == ')' && topDynArr(stack) == '(') popDynArr(stack);
			else if (c == ']' && topDynArr(stack) == '[') popDynArr(stack);
			else if (c == '}' && topDynArr(stack) == '{') popDynArr(stack);
			else return 0;
		}
	}
	if (ret_val) ret_val = !(isEmptyDynArr(stack));
	printf("return value %d\n", ret_val);
	deleteDynArr(stack);
	return ret_val;
}
Example #10
0
int main(int argc, const char * argv[])
{
	char cmd = ' ';
	DynArr* mainList = createDynArr(10);
	char filename[100]; //filename buffer
	FILE* file = NULL; //input/output file

	printf("\n\n** TO-DO LIST APPLICATION **\n\n");

	do
	{
		printf("Press:\n"
			"'l' to load to-do list from a file\n"
			"'s' to save to-do list to a file\n"
			"'a' to add a new task\n"
			"'g' to get the first task\n"
			"'r' to remove the first task\n"
			"'p' to print the list\n"
			"'e' to exit the program\n"
			);
		/* get input command (from the keyboard) */
		cmd = getchar();
		/* clear the trailing newline character */
		while (getchar() != '\n');

		switch (cmd)
		{
		case 'l':
		{
			//get filename
			printf("Enter filename: ");
			scanf("%s", filename);
			getchar();

			//if a file is already open, then close it
			if (file != NULL)
			{
				fclose(file);
			}

			file = fopen(filename, "r"); //open the file for reading

			if (file != NULL) //if the file was opened sucessfully...
			{
				//empty the main list
				if (!isEmptyDynArr(mainList))
				{
					int size = sizeDynArr(mainList);
					for (int i = 0; i < size; i++)
					{
						removeMinHeap(mainList, compare);
					}
				}

				//load the file and print a confirmation
				loadList(mainList, file); 
				printf("List has been loaded.\n\n");
			}
			else //otherwise print and error message
			{
				printf("Could not open file.\n\n");

			}
			break;
		}
		case 's':
		{
			//get filename
			printf("Enter filename: ");
			scanf("%s", filename);
			getchar();

			file = fopen(filename, "w"); //open the file for writing

			if (file != NULL) //if the file was opened sucessfully
			{
				//save the list and print a confirmation
				saveList(mainList, file);
				printf("List has been saved.\n\n");
			}
			else //otherwise print an error message
			{
				printf("Could not create file.\n\n");

			}
			break;
		}
		case 'a':
		{
			int priority; //stores the task priority
			char desc[100]; //sotres the task description

			//get the task description
			printf("Enter a brief description: ");
			fgets(desc, 100, stdin);
			desc[strcspn(desc, "\n")] = 0; //removes trailing newline character

			//get the task priority
			printf("Enter a task priority (0-999): ");
			scanf("%d", &priority);
			getchar();

			TYPE newTask = createTask(priority, desc); //create a new task
			addHeap(mainList, newTask, compare); //add that taks to the heap
			printf("The task '%s' has been added to your list.\n\n", desc); //print a confirmation
			break;
		}
		case 'g':
		{
			if (!isEmptyDynArr(mainList)) //make sure the list is not empty
			{
				struct Task* task = (struct Task*)getMinHeap(mainList); //get the value at the heap's root node
				printf("Your first task is: %s\n\n", task->description); //print the description of that value
			}
			else
			{
				printf("Your to-do list is empty!\n\n"); 
			}
			break;
		}
		case 'r':
		{
			if (!isEmptyDynArr(mainList)) //make sure the heap is not empty
			{
				struct Task* task = (struct Task*)getMinHeap(mainList); //get the value at the heap's root node
				printf("Your first task '%s' has been removed from the list.\n\n", task->description); //print the description of that value
				removeMinHeap(mainList, compare); //remove that value from the heap
				free(task);
				task = NULL;
				
			}
			else
			{
				printf("The list is empty.\n\n");
			}
			break;
		}
		case 'p':
		{
			if (!isEmptyDynArr(mainList)) //make sure the heap is not empty
			{
				printList(mainList); //then print the contents of the heap from highest to lowest priority
			}
			else
			{
				printf("The list is empty.\n\n");
			}
			break;
		}
		case 'e':
		{
			//if a file has been opened, then close that file
			if (file != NULL)
			{
				fclose(file);
			}
			break;
		}
		default:
			break;
		}
		/* Note: We have provided functions called printList(), saveList() and loadList() for you
		to use.  They can be found in toDoList.c */
	} while (cmd != 'e');
	/* delete the list */
	deleteDynArr(mainList);

	return 0;
}
Example #11
0
int main (int argc, const char * argv [])
{
    TYPE newTask, firstTask;
    char desc [ TASK_DESC_SIZE ], filename [ 50 ], *nlptr;
    int priority;
    char cmd = ' ';
    FILE *filePointer;
    DynArr * mainList = createDynArr(10);

    printf("\n\n** TO-DO LIST APPLICATION **\n\n");

    do
        {
        printf("Press:\n"
               "'l' to load to-do list from a file\n"
               "'s' to save to-do list to a file\n"
               "'a' to add a new task\n"
               "'g' to get the first task\n"
               "'r' to remove the first task\n"
               "'p' to print the list\n"
               "'e' to exit the program\n"
               );
        /* get input command (from the keyboard) */
        cmd = getchar();
        /* clear the trailing newline character */
        while( getchar() != '\n' ) ;

        switch( cmd )
            {
        case 'a': /* add new task */
            printf("Please enter the task description: ");
            /* get task description from user input (from keyboard) */
            if( fgets(desc, sizeof( desc ), stdin) != NULL )
                {
                /* remove trailing newline character */
                nlptr = strchr(desc, '\n');
                if( nlptr )
                    *nlptr = '\0';
                }
            /* get task priority from user input (from keyboard) */
            do {
                printf("Please enter the task priority (0-999): ");
                scanf("%d", &priority);
                } while( !( priority >= 0 && priority <= 999 ) );

            /* clear the trailing newline character */
            while( getchar() != '\n' ) ;

            /* create task and add the task to the heap */
            newTask = createTask(priority, desc);
            addHeap(mainList, newTask);
            printf("The task '%s' has been added to your to-do list.\n\n", desc);
            break;

        case 'g': /* get the first task */
            if( sizeDynArr(mainList) > 0 )
                {
                firstTask = getMinHeap(mainList);
                printf("Your first task is: %s\n\n", firstTask.description);
                }
            else
                printf("Your to-do list is empty!\n\n");

            break;

        case 'r': /* remove the first task */
            if( sizeDynArr(mainList) > 0 )
                {
                firstTask = getMinHeap(mainList);
                removeMinHeap(mainList);
                printf("Your first task '%s' has been removed from the list.\n\n", firstTask.description);
                }
            else
                printf("Your to-do list is empty!\n\n");

            break;

        case 'p': /* print the list */
            if( sizeDynArr(mainList) > 0 )
                {
                printList(mainList);
                }
            else
                printf("Your to-do list is empty!\n\n");

            break;


        case 's': /* save the list to file */
            if( sizeDynArr(mainList) > 0 )
                {
                /* get filename from user input (from keyboard) */
                printf("Please enter the filename: ");
                if( fgets(filename, sizeof( filename ), stdin) != NULL )
                    {
                    /* remove trailing newline character */
                    nlptr = strchr(filename, '\n');
                    if( nlptr )
                        *nlptr = '\0';
                    }
                /* open the file */
                filePointer = fopen(filename, "w");
                if( filePointer == NULL ) {
                    fprintf(stderr, "Cannot open %s\n", filename);
                    break;
                    }
                /* save the list to the file */
                saveList(mainList, filePointer);
                /* close the file */
                fclose(filePointer);
                printf("The list has been saved into the file successfully.\n\n");
                }
            else
                printf("Your to-do list is empty!\n\n");

            break;

        case 'l': /* load the list from the file */
            printf("Please enter the filename: ");
            /* get filename from user input (from keyboard) */
            if( fgets(filename, sizeof( filename ), stdin) != NULL )
                {
                /* remove trailing newline character */
                nlptr = strchr(filename, '\n');
                if( nlptr )
                    *nlptr = '\0';
                }
            /* open the file */
            filePointer = fopen(filename, "r");
            if( filePointer == NULL ) {
                fprintf(stderr, "Cannot open %s\n", filename);
                break;
                }
            /* load the list from the file */
            loadList(mainList, filePointer);
            /* close the file */
            fclose(filePointer);
            printf("The list has been loaded from file successfully.\n\n");
            break;

        case 'e': /* exit the program */
            printf("Bye!\n\n");
            break;

        default:
            printf("What is your command anyway?\n\n" );
            break;
            }
        }
    while( cmd != 'e' );
    /* delete the list */
    deleteDynArr(mainList);

    return 0;
}
Example #12
0
File: main.c Project: dot1q/Misc
int main (int argc, const char * argv[])
{
  char cmd = ' ';
  int priority;
  char str [256];
  DynArr* mainList = createDynArr(10);
  FILE *fp;

  printf("\n\n** TO-DO LIST APPLICATION **\n\n");

  do
    {
      printf("Press:\n"
             "'l' to load to-do list from a file\n"
             "'s' to save to-do list to a file\n"
             "'a' to add a new task\n"
             "'g' to get the first task\n"
             "'r' to remove the first task\n"
             "'p' to print the list\n"
             "'e' to exit the program\n"
             );
      /* get input command (from the keyboard) */
      cmd = getchar();
      /* clear the trailing newline character */
      while (getchar() != '\n');

	switch(cmd){
	case 'l':
		//load
		fp = fopen("todo.txt", "r");
		if(fp == NULL){
			printf("error opening file\n");
		}
		loadList(mainList, fp);
		fclose(fp);
		printf("List is loaded!\n");
		break;
		
	case 's':
		//save
		fp = fopen("todo.txt", "w");
		if(fp == NULL){
			printf("Error opening file!\n");
		}
		saveList(mainList, fp);
		fclose(fp);
		printf("List is saved!\n");
		break;
	case 'a':
                printf("Enter a description: ");
		fgets(str, 256, stdin);
		if ((strlen(str)>0) && (str[strlen (str) - 1] == '\n'))
			str[strlen (str) - 1] = '\0';
		printf("Enter the priority: ");
		scanf("%d", &priority);
                TYPE taskTemp = createTask(priority, str);
                addHeap(mainList, taskTemp, compare);
		printf("Item added! \n\n");
		while (getchar() != '\n');
		break;
	case 'g':
		if(sizeDynArr(mainList) > 0){
			print_type(getMinHeap(mainList));
		}else{
			printf("List is empty!\n");
		}
		break;
	case 'r':
		if(sizeDynArr(mainList) > 0){
			removeMinHeap(mainList, compare);
		}else{
			printf("No items in list!\n");
		}
		break;
	case 'p':
		if(sizeDynArr(mainList) > 0){
			printList(mainList);
		}else{
			printf("List has no items!\n");
		}
		break;
	case 'e':
		break;
	default:
		printf("Please enter a proper value!\n");
		break;
	}
	

    }
  while(cmd != 'e');
  /* delete the list */
  deleteDynArr(mainList);

  return 0;
}
Example #13
0
int main(int argc, char **argv){
	char *temps;
	char c;
	char *arName = "";
        int  verbose = 0;
	int  nextArg = 0;
        int  fd;
	int fileLen =0;
	char buffer[60];
	int  i =0;
	long  j =0;
	int k =0;
	double  tempSum;
	int fdDestination;	
	char *fileBuffer = NULL;
	int num_read;
	int found[argc];
	struct tm *time;
	struct ar_hdr header;
	struct dirent **namelist;
	struct arFiles arF;

	while ((c = getopt(argc, argv, "q:x:v:d:A:wt:")) != -1){
		switch (c)
		{
			case 'q'://appends new file to end of archive
				arName = optarg;
				nextArg = optind;
				
				if(nextArg>=argc){
					fprintf(stderr, "Too few arguments\nUsage: %s ar {qxvdAwt} archive-file file...\n", argv[0]);
					exit(EXIT_FAILURE);
				}

				openArchiveWrite(&fd, arName);
				lseek(fd,0, SEEK_END);

				while (nextArg<argc){
					temps = argv[nextArg];
					appendFile(fd, temps);
					nextArg++;
				}
				close(fd);

				break;
	 		case 'x'://extracts a file
				arName = optarg;
				nextArg = optind;
				openArchiveRead(&fd, arName);
				
				for(i = 0; i<argc;i++)
					found[i]=0;

				while (nextArg<argc){

					while (getHeadder(fd, &header)){
						temps = NULL;
						temps = strtok(header.ar_name, "/");
						fileLen = atoi(header.ar_size);
						if(fileLen%2 != 0)
							fileLen++;

						if(strcmp(temps, argv[nextArg])==0){

							tempSum=0;

							for(i=5;i>2;i--){//base conversion for modes
								buffer[0] = header.ar_mode[i];
								buffer[1]= 0;
								tempSum += atoi(buffer)*pow(8.0,5-i);

							}
							
							//read archived file into memory
							fileLen = atoi(header.ar_size);
							fileBuffer = (char *)malloc(fileLen);
							num_read = read(fd, fileBuffer, fileLen);
							if (num_read < 0)
							{
								close(fd);
								perror("Error while reading the file to add to extract.\n");
								exit(EXIT_FAILURE);
							}

							//create the archived file 
							i = tempSum;
							fdDestination = open(temps, O_RDWR|O_CREAT, i);
							if(fdDestination<0){
								free(fileBuffer);
								close(fd);
								perror("Error while creating the extracted file.");
								exit(EXIT_FAILURE);
							}

							//write the archived file to disk
							num_read = write(fdDestination, fileBuffer, fileLen);
							if (num_read < 0)
							{
								close(fd);
								perror("Error while writing the extracted file.\n");
								exit(EXIT_FAILURE);
							}

							free(fileBuffer);
							close(fdDestination);
							break;
						}
						lseek(fd, fileLen, SEEK_CUR);					
					}	
					lseek(fd, 8, SEEK_SET);				
					nextArg++;
				}

				close(fd);
				break;
			case 'v'://set verbose to 1 and cascade to -t
				verbose=1;
			case 't':
				arName = optarg;
				openArchiveRead(&fd, arName);

				while (getHeadder(fd, &header)){
					
					if(verbose){//accounts for -v
						tempSum=0;
						for(i=5;i>2;i--){//convert mode base
							buffer[0] = header.ar_mode[i];
							buffer[1]= 0;
							tempSum += atoi(buffer)*pow(8.0,5-i);
						}
						
						//write permissions
						filePerms(tempSum);

						//write GID/UID
						printf("%d/", atoi(header.ar_gid));
						printf("%d ", atoi(header.ar_uid));
						
						//store the size string
						k = atoi(header.ar_size);
						snprintf(buffer, 10, "%d", k);
						k= strlen(buffer);
						
						//ar displays 6 places for size unless larger than 6 places
						if(k<6){
							j = 6;
						} else{
							j = k;//if larger than 6 display up to 10 places (limit of .ar_size)
						}

						//print size right justified
						for(i=0;i<j;i++){
							buffer[i] = (i+k<j)?' ': header.ar_size[(i+k-j)];
							
						}
						buffer[j]= 0;
						printf("%s ", buffer); 
					
						//convert time to tm struct and write custom formated time
						j = atoi(header.ar_date);
						time = localtime(&j);
						strftime(buffer, 60, "%b %e %H:%M %Y", time);
						printf("%s ",buffer);
		
					}
			
					//the first token indicated by / is the file name
					temps = strtok(header.ar_name, "/");
		     			printf("%s\n",temps);
					
					//move the file pointer to where the next header should exist
					fileLen = atoi(header.ar_size);	
					if(fileLen%2 != 0)
						fileLen++;
					lseek(fd, fileLen, SEEK_CUR);
				}
				close(fd);
				break;
	           	case 'd'://removes a file from the archive
				arName = optarg;
				nextArg = optind;
				openArchiveRead(&fd, arName);
				
				//find all locations to delete
				while (nextArg<argc){

					while (getHeadder(fd, &header)){
						temps = NULL;
						temps = strtok(header.ar_name, "/");
						fileLen = atoi(header.ar_size);
						if(fileLen%2 != 0)
							fileLen++;

						if(strcmp(temps, argv[nextArg])==0){
							found[nextArg] = 1;
							break;
						}
						lseek(fd, fileLen, SEEK_CUR);					
					}	
					lseek(fd, 8, SEEK_SET);				
					nextArg++;
				}
	
				//check to see if at least one file was found
				k=0;
				for(i=0;i<argc;i++)
					k = (k|found[i]);

				if(k){//get each file info
					char *fileData;
					struct DynArr *fileArray;
					fileArray = createDynArr(10);
					
					while (getHeadder(fd, &header)){
						
						fileLen = atoi(header.ar_size);
						if(fileLen%2 != 0)
							fileLen++;
						fileData = (char *)malloc(fileLen+60);

						lseek(fd, -60, SEEK_CUR);
						num_read = read(fd, fileData, fileLen+60);
						if (num_read < 0)
						{
							close(fd);
							perror("Error while reading the archive prior to delete.\n");
							exit(EXIT_FAILURE);
						}
						
						//add filedata to array
						arF.fileName = (char *)malloc(15);
						char *temp = strtok(header.ar_name, "/");
						strncpy(arF.fileName, temp, 15);
						arF.fileSize = fileLen+60;
						arF.file = fileData;
						addDynArr(fileArray, arF);
						

					}
					
					//close the current file and re-open it deleting it's contents
					close(fd);
					openArchiveDelete(&fd, arName);

					//iterate through each file saved in fileArray
					int numFiles = sizeDynArr(fileArray);
					for(i=0;i<numFiles;i++){
						arF = getDynArr(fileArray, i);
						for(k=0;k<argc;k++){
							if(found[k] && (strcmp(arF.fileName, argv[k])==0)){

								found[k] = 0;//turn off the found flag to stop searching after the first file is found
								k=argc+1;// break out of the loop
							}	
						}
						//if k==argc then the file was not on the list to be deleted so write it
						if(k==argc){
							num_read = write(fd, arF.file, arF.fileSize);
							if (num_read < 0)
							{
								close(fd);
								perror("Error while writing the updated archive file.\n");
								exit(EXIT_FAILURE);
							}
						}
					}

					deleteDynArr(fileArray);
					close(fd);
				} else{
					close(fd);
				}
	             		break;
	           	case 'A'://most of the code for getting the file listing comes from the scandir man page
				arName = optarg;
				k = scandir(".", &namelist, NULL, alphasort);
				if(k<0){
					perror("Failed to get directory listing.");
					exit(EXIT_FAILURE);
				}
				
				openArchiveWrite(&fd, arName);
				lseek(fd,0, SEEK_END);

				for(i =0;i<k;i++){
		
					if((strcmp(namelist[i]->d_name, arName)!=0)&&namelist[i]->d_type== DT_REG){
						appendFile(fd, namelist[i]->d_name);
					}
				}

				close(fd);
				free(namelist);
	             		break;
	           	case 'w':
	             		break;
	           	default:
		     		fprintf(stderr, "Usage: %s ar {qxvdAwt} archive-file file...\n", argv[0]);
	            		exit(EXIT_FAILURE);
		}
	}

   return 0;
}
Example #14
0
/* Checks whether the (), {}, and [] are balanced or not
	param: 	s pointer to a string
	pre: s is not null
	post: Returns 1 or 0 and displays corresponding response in main
*/
int isBalanced(char* s)
{
	/* FIXME: You will write this function */
	if (s == 0)
		return 0;
	char ch;

	struct DynArr *balArray = newDynArr(10);
	while((ch = nextChar(s)) != '\0')
	{
		
		//printf("%c\n",ch);	//test statement 
		
		//Push when ch = [,{,( 
		if(ch == '[' || ch == '(' || ch == '{')
			pushDynArr(balArray, ch);

		//Pop when ],},) and when array is not empty
		if(ch == ']' || ch == ')' || ch == '}')
		{		
			if (isEmptyDynArr(balArray))
				return 0;
			//Check the individual situations and pop if matching
			if (ch == ']')
			{
				if (topDynArr(balArray) == '[')
				{
					popDynArr(balArray);
					

				}
				else
					return 0;
				
			}
			else if (ch == '}') 
			{
				if (topDynArr(balArray) == '{')
				{
					popDynArr(balArray);
				}
				else
					return 0;
			}
			else if (ch == ')')
			{
				if (topDynArr(balArray) == '(')
				{
					popDynArr(balArray);
				}
				else
					return 0;
			}
			
				
		}
		//printf("%d", sizeDynArr(balArray));//  test statement
		//printf("Top of Stack: %c\n", topDynArr(balArray));// test statement
	}
	
	 	

		
	if (!isEmptyDynArr(balArray))
	{
		return 0;
	}
	else
	{
		deleteDynArr(balArray);
		return 1;
	}

	
}
int main (int argc, const char * argv[])
{
    char cmd[1] = " ";
    char  filename[128];
    FILE *a_file;

    int priority;
    char task[128];
    struct Task * tempTask;
    DynArr* mainList = createDynArr(10);

    printf("\n\n** TO-DO LIST APPLICATION **\n\n");

    do
        {
            printf("Press:\n"
                 "'l' to load to-do list from a file\n"
                 "'s' to save to-do list to a file\n"
                 "'a' to add a new task\n"
                 "'g' to get the first task\n"
                 "'r' to remove the first task\n"
                 "'p' to print the list\n"
                 "'e' to exit the program\n"
                 );
          /* get input command (from the keyboard) */
            scanf("%s", cmd);
          /* clear the trailing newline character */
            while (getchar() != '\n');

          /* Fixme:  Your logic goes here! */
            if(cmd[0] == 'l'){
                printf("Please enter a file name to load:");
                scanf("%s", filename);
                a_file = fopen(filename, "r");
                loadList(mainList, a_file);
                printf("File loaded\n");
                }

            else if(cmd[0] == 's'){
                printf("Please enter the file name:");
                scanf("%s", filename);
                a_file = fopen(filename, "w");
                saveList(mainList, a_file);
                printf("File saved.\n");
                }

            else if(cmd[0] == 'a'){
                printf("Please enter the task name: ");
                scanf("%s", task);
                printf("Please enter the task priority: ");
                scanf("%d", &priority);
                tempTask = createTask(priority, task);

                addHeap(mainList, tempTask, compare);
                }

            else if(cmd[0] == 'g'){
                if (sizeDynArr(mainList) > 0){
                    tempTask = getMinHeap(mainList);
                    printf("The first task on the list is: %s\n", tempTask->description);
                }
                else
                    printf("Your to-do list is empty.\n");
            }

            else if(cmd[0] == 'r'){

                if (sizeDynArr(mainList) > 0){
                    tempTask = getMinHeap(mainList);
                    removeMinHeap(mainList, compare);
                    printf("The first task (%s) has been removed from the list.\n", tempTask->description);
                    free(tempTask);
                  }
                else
                    printf("Your to-do list is empty, so nothing was removed.\n");
                }

            else if(cmd[0] == 'p'){
                if (sizeDynArr(mainList) > 0){
                    printDynArr(mainList, print_type);
                    }
                else
                    printf("Your to-do list is empty.\n");
                }
            } while(cmd[0] != 'e');
          /* Note: We have provided functions called printList(), saveList() and loadList() for you
             to use.  They can be found in toDoList.c */


      /* delete the list */
      deleteDynArr(mainList);

      return 0;
}