コード例 #1
0
ファイル: GraphTest.c プロジェクト: jinyanli/CMPS101
int main(int argc, char* argv[]){
   int i, s, max, min, d, n=35;
   //int n=35;
   List  C = newList(); // central vertices
   List  P = newList(); // peripheral vertices
   List  E = newList(); // eccentricities
   Graph G = newGraph(n);


   // Build graph G

   for(i=1; i<n; i++){
      if( i%7!=0 )
        addEdge(G, i, i+1);
      if( i<=28  )
       addEdge(G, i, i+7);
   }
   addEdge(G, 9, 31);
   addEdge(G, 17, 13);
   addEdge(G, 14, 33);

   // Print adjacency list representation of G
   printGraph(stdout, G);

   // Calculate the eccentricity of each vertex
   for(s=1; s<=n; s++){
      BFS(G, s);
      max = getDist(G, 1);
      for(i=2; i<=n; i++){
         d = getDist(G, i);
         max = ( max<d ? d : max );
      }
      append(E, max);
   }
printf("Source of G %d Size of G %d Order of G %d",getSource(G),getSize(G),getOrder(G));

   // Determine the Radius and Diameter of G, as well as the Central and
   // Peripheral vertices.
   append(C, 1);
   append(P, 1);
   min = max = front(E);
   moveTo(E,0);
   moveNext(E);
   for(i=2; i<=n; i++){
      d = getElement(E);
      if( d==min ){
         append(C, i);
      }else if( d<min ){
         min = d;
         clear(C);
         append(C, i);
      }
      if( d==max ){
         append(P, i);
      }else if( d>max ){
         max = d;
         clear(P);
         append(P, i);
      }
      moveNext(E);
   }

   // Print results
   printf("\n");
   printf("Radius = %d\n", min);
   printf("Central vert%s: ", length(C)==1?"ex":"ices");
   printList(stdout, C);
   printf("\n");
   printf("Diameter = %d\n", max);
   printf("Peripheral vert%s: ", length(P)==1?"ex":"ices");
   printList(stdout, P);
   printf("\n");

   freeList(&C);
   freeList(&P);
   freeList(&E);
   freeGraph(&G);
//testing undirected graph
printf("testing undirected graph G2\n");
  Graph G2= newGraph(6);
   addEdge(G2, 1, 2);
   addEdge(G2, 1, 3);
   addEdge(G2, 2, 4);
   addEdge(G2, 2, 5);
   addEdge(G2, 2, 6);
   addEdge(G2, 3, 4);
   addEdge(G2, 4, 5);
   addEdge(G2, 5, 6);

   //test access functions
    printGraph(stdout, G2);
    BFS(G2, 3);

printf("Source of G2:%d Size of G2:%d Order of G2:%d \n",getSource(G2),getSize(G2),getOrder(G2));
printf("getParent(G2,6)%d\n",getParent(G2,6));
List Pa=newList();
printf("getDist 3 to 6:%d\n",getDist(G2,6));
printf("getPath 3 to 6:\n");
getPath(Pa,G2,6);
printList(stdout,Pa);

BFS(G2, 1);
printf("getDist 1 to 5:%d\n",getDist(G2,5));
clear(Pa);
getPath(Pa,G2,5);
printf("getPath 1 to 5:\n");
printList(stdout,Pa);

printf("makeNull(G2)\n");
makeNull(G2);
printGraph(stdout, G2);
printf("Source of G:%d Size of G:%d Order of G:%d \n",getSource(G2),getSize(G2),getOrder(G2));
printf("getParent(G2,5)%d\n",getParent(G2,5));
printf("getDist(G2,6)%d\n",getDist(G2,6));

   freeList(&Pa);
   freeGraph(&G2);


//testing directed graph
printf("\ntesting directed graph G3\n");
Graph G3=newGraph(4);

addArc(G3,1,2);
addArc(G3,1,3);
addArc(G3,3,2);
addArc(G3,3,4);
addArc(G3,4,1);

  //test access functions
printGraph(stdout, G3);
   BFS(G3, 3);

printf("Source of G3:%d Size of G3:%d Order of G3:%d \n",getSource(G3),getSize(G3),getOrder(G3));
printf("getDist 3 to 6:%d\n",getDist(G3,1));
printf("getDist 3 to 2:%d\n",getDist(G3,2));
printf("getParent(3):%d\n",getParent(G3,3));


List Pa2=newList();
printf("getPath 3 to 1:\n");
getPath(Pa2,G3,1);
printList(stdout,Pa2);
printf("getParent(1):%d\n",getParent(G3,1));


   // Free objects


   freeList(&Pa2);
   freeGraph(&G3);

   return(0);
}
コード例 #2
0
ファイル: taskBarApp.cpp プロジェクト: akhildabral/AppGrabber
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{

    LPNMTOOLBAR lPEvent;
    LPNMTBGETINFOTIP lptbgit;
    LPNMMOUSE lpnm;
    LPNMTBDISPINFO lptbdi;
    LPNMKEY lpnmk;
    HDESK a, b, z;
    DWORD tid;
    DWORD pid;


	//--------------------- Windows Hook Events--------------------

    if (message == WM_SHELLHOOKMESSAGE) {
	switch (LOWORD(wParam)) {
	case HSHELL_WINDOWCREATED:
	    AddToList(hWnd, lParam, "HSHELL_WINDOWCREATED");
	    break;
	case HSHELL_WINDOWDESTROYED:
	    RemoveFromList(hWnd, lParam, "HSHELL_WINDOWDESTROYED");
	    break;
	}
	return 0;
    }
	//---------------------------------------------------------------

    switch (message) {


    case WM_MYBUTTON:
    case WM_COMMAND:
	wmId = LOWORD(wParam);
	wmEvent = HIWORD(wParam);
	// Parse the menu selections:
	newhWnd = (HWND) lParam;
	lPEvent = (LPNMTOOLBAR) lParam;
	lptbgit = (LPNMTBGETINFOTIP) lParam;
	lptbdi = (LPNMTBDISPINFO) lParam;
	lpnm = (LPNMMOUSE) lParam;

	if (HIWORD(wParam) == EN_CHANGE) {
	    Search((HWND) lParam);
	}

	switch (wmId) {

	case ID_PORT_BUTTON:								// When Button Pressed
	    OutputDebugString(L"Button Pressed \n");

	    break;
	case IDM_ABOUT:
	    DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
	    break;
	case IDM_EXIT:
	    DestroyWindow(hWnd);
	    break;
	default:
	    return DefWindowProc(hWnd, message, wParam, lParam);
	}
	break;
    case WM_PAINT:
	GetClientRect(hWnd, &rect);
	hdc = BeginPaint(hWnd, &ps);
	// TODO: Add any drawing code here...
	OutputDebugStringW(L"In Paint");

	EndPaint(hWnd, &ps);
	break;
    case WM_DESTROY:
	freeList();
	ImageList_Remove(g_hImageList, -1);
	ImageList_Destroy(g_hImageList);
	DestroyWindow(hWndToolbar);
	UnSetShellHook(hWnd);
	PostQuitMessage(0);
	break;
    case WM_NOTIFY:											// Capture Notification Messages

	lptbgit = (LPNMTBGETINFOTIP) lParam;
	lPEvent = (LPNMTOOLBAR) lParam;
	lpnm = (LPNMMOUSE) lParam;
	lptbdi = (LPNMTBDISPINFO) lParam;
	newhWnd = (HWND) lParam;
	lpnmk = (LPNMKEY) lParam;



	TCHAR szText[0x1000];
	switch (lPEvent->hdr.code) {
	case TBN_DROPDOWN:										//When Dropdown Button Pressed
	    OutputDebugString(L"Dropdown Pressed \n");
	    {
		// Get the coordinates of the button.
		RECT rc;
		if (!SendMessage(lPEvent->hdr.hwndFrom, TB_GETRECT, (WPARAM) lPEvent->iItem, (LPARAM) & rc))
		    OutputDebugString(L"Error get rect");

		// Convert to screen coordinates.            
		MapWindowPoints(lPEvent->hdr.hwndFrom, HWND_DESKTOP, (LPPOINT) & rc, 2);

		// Get the menu.
		HMENU hMenuLoaded = LoadMenu(hInst, MAKEINTRESOURCE(IDR_MENU2));

		HICON hIcon = (HICON) GetClassLong((HWND) lPEvent->tbButton.iBitmap, GCL_HICON);

		GetWindowText(((HWND) lPEvent->tbButton.dwData), szText, sizeof(szText));
		// Get the submenu for the first menu item.
		HMENU hPopupMenu = GetSubMenu(hMenuLoaded, 0);
		AppendMenu(hPopupMenu, MF_STRING, 0, szText);




		TPMPARAMS tpm;

		tpm.cbSize = sizeof(TPMPARAMS);
		tpm.rcExclude = rc;




		TrackPopupMenuEx(hPopupMenu, TPM_LEFTALIGN | TPM_LEFTBUTTON | TPM_VERTICAL, rc.left, rc.bottom, hWnd, &tpm);



		return TRUE;

	    }
	    break;
	    //case TBN_GETINFOTIP : 


	default:
	    break;
	}
	switch (lptbgit->hdr.code) {
	case TBN_GETINFOTIP:
	    OutputDebugString(TEXT("ToolTip Info \n"));
	    break;
	default:
	    break;
	}
	switch (lPEvent->hdr.code) {
		 HDESK b;

	case NM_CLICK:											// When Taskbar Button Pressed
	    OutputDebugString(L"ButtonPressed ");
		 b = GetThreadDesktop(GetCurrentThreadId());
	   /* tid = GetWindowThreadProcessId((HWND) lPEvent->tbButton.iBitmap, &pid);
	    a = GetThreadDesktop(tid);
	    b = GetThreadDesktop(GetCurrentThreadId());
	    if (GetThreadDesktop(tid) != GetThreadDesktop(GetCurrentThreadId())) {
		SwitchDesktop((HDESK) a);
		ShowWindow(((HWND) lPEvent->tbButton.iBitmap), SW_RESTORE);
		SetForegroundWindow((HWND) lPEvent->tbButton.iBitmap);
		break;
	    }

	    if (IsIconic(((HWND) lPEvent->tbButton.iBitmap)))
		ShowWindow(((HWND) lPEvent->tbButton.iBitmap), SW_RESTORE);
	    else
		ShowWindow(((HWND) lPEvent->tbButton.iBitmap), SW_MINIMIZE);

		*/
		if(GetParent((HWND) lPEvent->tbButton.iBitmap) != hWnd)
		SetParent((HWND) lPEvent->tbButton.iBitmap,hWnd);
		else
			SetParent((HWND) lPEvent->tbButton.iBitmap,NULL);
	    break;


	default:
	    break;
	}
	


	break;


    case WM_CREATE:
	break;




    default:

	return DefWindowProc(hWnd, message, wParam, lParam);
    }
    return 0;
}
コード例 #3
0
int performLivenessOnBlock(t_basic_block *bblock, t_list *out)
{
   t_list *current_element;
   t_list *cloned_list;
   t_cflow_Node *next_node;
   t_cflow_Node *current_node;
   int modified;

   /* initialize the local variables */
   modified = 0;

   if (bblock == NULL || bblock->nodes == NULL) {
      cflow_errorcode = CFLOW_INVALID_BBLOCK;
      return modified;
   }

   current_element = getLastElement(bblock->nodes);
   current_node = (t_cflow_Node *) LDATA(current_element);
   assert(current_node != NULL);

   /* update the out set */
   current_node->out = addListToSet
         (current_node->out, out, NULL, &modified);

   /* update the in list */
   cloned_list = cloneList(current_node->out);
   
#if CFLOW_ALWAYS_LIVEIN_R0 == (1)
   if ((current_node->uses)[0] != NULL && (current_node->uses)[0]->ID != REG_0)
      cloned_list = addVariableToSet
            (cloned_list, (current_node->uses)[0], NULL);
   if ((current_node->uses)[1] != NULL && (current_node->uses)[1]->ID != REG_0)
      cloned_list = addVariableToSet
            (cloned_list, (current_node->uses)[1], NULL);
   if ((current_node->uses)[2] != NULL && (current_node->uses)[2]->ID != REG_0)
      cloned_list = addVariableToSet
            (cloned_list, (current_node->uses)[2], NULL);
#else
   if ((current_node->uses)[0] != NULL)
      cloned_list = addVariableToSet
            (cloned_list, (current_node->uses)[0], NULL);
   if ((current_node->uses)[1] != NULL)
      cloned_list = addVariableToSet
            (cloned_list, (current_node->uses)[1], NULL);
   
   if ((current_node->uses)[2] != NULL)
      cloned_list = addVariableToSet
            (cloned_list, (current_node->uses)[2], NULL);
#endif



#if CFLOW_ALWAYS_LIVEIN_R0 == (1)
   if (current_node->def != NULL && (current_node->def)->ID != REG_0)
#else
   if (current_node->def != NULL)
#endif
   {
      int found = 0;
      int current_use_idx = 0;
      
      do
      {
         if ((current_node->uses)[current_use_idx] != NULL)
         {
            if ((current_node->uses)[current_use_idx]->ID == current_node->def->ID)
               found = 1;
         }
         
         current_use_idx++;
         
      } while((found == 0) && (current_use_idx < 3));
      
      if (!found)
         cloned_list = removeElement(cloned_list, current_node->def);
   }
   
   current_node->in = addListToSet
         (current_node->in, cloned_list, NULL, &modified);

   /* remove the cloned list */
   freeList(cloned_list);
   
   /* set the new value of next_node */
   next_node = current_node;
   current_element = LPREV(current_element);
   while (current_element != NULL)
   {
      /* take a new node */
      current_node = (t_cflow_Node *) LDATA(current_element);
      assert(current_node != NULL);

      /* clone the `in' list of the next_node */
      cloned_list = cloneList(next_node->in);
      
      /* update the out list */
      current_node->out = addListToSet
            (current_node->out, cloned_list, NULL, &modified);
      
      /* remove the cloned list */
      freeList(cloned_list);

      /* clone the `in' list of the next_node */
      cloned_list = cloneList(current_node->out);
      
      /* update the in list */
#if CFLOW_ALWAYS_LIVEIN_R0 == (1)
      if ((current_node->uses)[0] != NULL && (current_node->uses)[0]->ID != REG_0)
         cloned_list = addVariableToSet
               (cloned_list, (current_node->uses)[0], NULL);
      if ((current_node->uses)[1] != NULL && (current_node->uses)[1]->ID != REG_0)
         cloned_list = addVariableToSet
               (cloned_list, (current_node->uses)[1], NULL);
      if ((current_node->uses)[2] != NULL && (current_node->uses)[2]->ID != REG_0)
         cloned_list = addVariableToSet
               (cloned_list, (current_node->uses)[2], NULL);
#else
      if ((current_node->uses)[0] != NULL)
         cloned_list = addVariableToSet
               (cloned_list, (current_node->uses)[0], NULL);
      if ((current_node->uses)[1] != NULL)
         cloned_list = addVariableToSet
               (cloned_list, (current_node->uses)[1], NULL);
      if ((current_node->uses)[2] != NULL)
         cloned_list = addVariableToSet
               (cloned_list, (current_node->uses)[2], NULL);
#endif
      
#if CFLOW_ALWAYS_LIVEIN_R0 == (1)
      if (current_node->def != NULL && (current_node->def)->ID != REG_0)
#else
      if (current_node->def != NULL)
#endif
      {
         int found = 0;
         int current_use_idx = 0;
      
         do
         {
            if ((current_node->uses)[current_use_idx] != NULL)
            {
               if ((current_node->uses)[current_use_idx]->ID
                        == current_node->def->ID)
               {
                  found = 1;
               }
            }
            current_use_idx++;
         
         } while((found == 0) && (current_use_idx < 3));
      
         if (!found)
            cloned_list = removeElement(cloned_list, current_node->def);
      }

      current_node->in = addListToSet
            (current_node->in, cloned_list, NULL, &modified);

      /* remove the cloned list */
      freeList(cloned_list);
      
      /* update the loop control informations */
      current_element = LPREV(current_element);
      next_node = current_node;
   }

   /* return the `modified' value */
   return modified;
}
コード例 #4
0
int main(int argc, char* argv[]){
   int i, s, max, min, d, n=35;
   List  C = newList(); // central vertices 
   List  P = newList(); // peripheral vertices 
   List  E = newList(); // eccentricities 
   Graph G = NULL;

   // Build graph G 
   G = newGraph(n);
   for(i=1; i<n; i++){
      if( i%7!=0 ) addEdge(G, i, i+1);
      if( i<=28  ) addEdge(G, i, i+7);
   }
   addEdge(G, 9, 31);
   addEdge(G, 17, 13);
   addEdge(G, 14, 33);

   // Print adjacency list representation of G
   printGraph(stdout, G);

   // Calculate the eccentricity of each vertex 
   for(s=1; s<=n; s++){
      BFS(G, s);
      max = getDist(G, 1);
      for(i=2; i<=n; i++){
         d = getDist(G, i);
         max = ( max<d ? d : max );
      }
      append(E, max);
   }

   // Determine the Radius and Diameter of G, as well as the Central and 
   // Peripheral vertices.
   append(C, 1);
   append(P, 1);
   min = max = front(E);
   moveTo(E,0);
   moveNext(E);
   for(i=2; i<=n; i++){
      d = getElement(E);
      if( d==min ){
         append(C, i);
      }else if( d<min ){
         min = d;
         clear(C);
         append(C, i);
      }
      if( d==max ){
         append(P, i);
      }else if( d>max ){
         max = d;
         clear(P);
         append(P, i);
      }
      moveNext(E);
   }

   // Print results 
   printf("\n");
   printf("Radius = %d\n", min);
   printf("Central vert%s: ", length(C)==1?"ex":"ices");
   printList(stdout, C);
   printf("\n");
   printf("Diameter = %d\n", max);
   printf("Peripheral vert%s: ", length(P)==1?"ex":"ices");
   printList(stdout, P);
   printf("\n");

   // Free objects 
   freeList(&C);
   freeList(&P);
   freeList(&E);
   freeGraph(&G);

   return(0);
}
コード例 #5
0
ファイル: GraphTest.c プロジェクト: jszalaha/CMPS-101-Java-C
int main(int argc, char * argv[]){

    List path = newList();

    Graph G = newGraph(5);
    Graph H = newGraph(10);

    printf("%d\n", getOrder(G));
    printf("%d\n", getOrder(H));
    printf("%d\n", getSize(G));

    for(int i = 1; i < getOrder(G)-1; i++){
        addEdge(G, i, i+1);
        printf("%d\n", getSize(G));
    }
    printf("%d\n", getSize(G));

    printf("%d\n", getSize(H));
    for(int i = 1; i < getOrder(H)-2; i++){
        addEdge(H, i, i+1);
        addEdge(H, i, i+2);
    }
    printf("%d\n", getSize(H));

    printf("%d\n", getSource(G));
    printf("%d\n", getParent(G, 5));
    printf("%d\n", getDist(G, 5));
    printGraph(stdout, G);

    printf("%d\n", getSource(H));
    printf("%d\n", getParent(H, 10));
    printf("%d\n", getDist(H, 10));
    printGraph(stdout, H);

    BFS(G, 1);
    printf("%d\n", getSource(G));
    printf("%d\n", getParent(G, 5));
    printf("%d\n", getDist(G, 5));

    getPath(path, G, 5);
    printList(stdout, path);

    clear(path);
    printList(stdout, path);

    BFS(H, 5);
    printf("\n");
    printf("%d\n", getSource(H));
    printf("%d\n", getParent(H, 10));
    printf("%d\n", getDist(H, 10));
    printf("%d\n", getParent(H, 8));
    printf("%d\n", getParent(H, 6));
    printf("%d\n", getParent(H, 5));

    getPath(path, H, 10);
    printList(stdout, path);

    makeNull(G);
    makeNull(H);
    printf("%d\n", getSize(G));
    printf("%d\n", getSize(H));

    freeGraph(&G);
    freeGraph(&H);
    freeList(&path);

    printf("globalAlloc = %d\n", globalAlloc);

    return 0;
}
コード例 #6
0
ファイル: GraphTest.c プロジェクト: eriiikjung/UCSC_CS101
int main(int argc, char* argv[]){
  


   int i, s, max, min, d, n=35;
   List  C = newList(); // central vertices 
   List  P = newList(); // peripheral vertices 
   List  E = newList(); // eccentricities 
   Graph G = NULL;

   // Build graph G 
   G = newGraph(n);
   for(i=1; i<n; i++){ 
     if( i%7!=0 ) addEdge(G, i, i+1);
      if( i<=28  ) addEdge(G, i, i+7);
   }
   addEdge(G, 9, 31);
   addEdge(G, 17, 13);
   addEdge(G, 14, 33);

   // Print adjacency list representation of G
   printGraph(stdout, G);

   // Calculate the eccentricity of each vertex 
   for(s=1; s<=n; s++){
      BFS(G, s);
      max = getDist(G, 1);
      for(i=2; i<=n; i++){
         d = getDist(G, i);
         max = ( max<d ? d : max );
      }
      append(E, max);
   }
   
   // Determine the Radius and Diameter of G, as well as the Central and 
   // Peripheral vertices.
   append(C, 1);
   append(P, 1);
   min = max = front(E);
   moveTo(E,0);
   moveNext(E);
   for(i=2; i<=n; i++){
      d = getElement(E);
      if( d==min ){
         append(C, i);
      }else if( d<min ){
         min = d;
         clear(C);
         append(C, i);
      }
      if( d==max ){
         append(P, i);
      }else if( d>max ){
         max = d;
         clear(P);
         append(P, i);
      }
      moveNext(E);
   }

   // Print results 
   printf("\n");
   printf("Radius = %d\n", min);
   printf("Central vert%s: ", length(C)==1?"ex":"ices");
   printList(stdout, C);
   printf("\n");
   printf("Diameter = %d\n", max);
   printf("Peripheral vert%s: ", length(P)==1?"ex":"ices");
   printList(stdout, P);
   printf("\n");
   printf("--------------This concludes the given test by professor\n");
   // recomputes BFS with source vertex
   BFS(G, 2);
   clear(C);
   clear(P);
   getPath(C, G, 35);
   getPath(P, G, 2);
   // prints out computed paths and distances
   printf("The path from source to vertex 35(the source vertex): ");
   printList(stdout, C);
   printf("\nThe distance from source to vertex 35( the source vertex): ");
   printf("%d\n", getDist(G, 35));
   printf("\nThe path from source to vertex 2: ");
   printList(stdout, P);
   printf("\nThe distance from source to vertex 2( the source vertex): ");
   printf("%d\n", getDist(G, 2));
   printf("\n");
   
   // Free objects
   
   clear(C);
   clear(P);
   freeGraph(&G);
   //re-build graph G
   n = 100;
   G = newGraph(n);
   for(i = 1; i<n; i++){
     if(i%10 !=0) addEdge(G,i,i+1);
     if(i<=50) addArc(G, i, i+10);
   }
   addArc(G,9,31);
   addEdge(G,17,13);
   addArc(G,14,33);
   
   // recomputes BFS with source vertex
   BFS(G, 50);

   getPath(C, G, 50);
   getPath(P, G, 99);
   printGraph(stdout, G);
   printf("The path from source to vertex 50(the source vertex):");
   printList(stdout, C);
   printf("\nThe distance from source to vertex 50 (the source vertex):");
   printf("%d\n", getDist(G, 50));
   printf("\nThe path from source to vertex 99: ");
   printList(stdout, P);
   printf("\nThe distance from source to vertex 99: ");
   printf("%d\n", getDist(G,99));
   printf("\n");

   freeList(&C);

   
   freeList(&P);

   
   freeList(&E);
   freeGraph(&G);
   
   return(0);
}
コード例 #7
0
/* Main Routine */
void main()
{
	struct dubLinkList *head= NULL,*temp=NULL;
	int more=1,d=0,data=0, a = 0;
	position pos = LIST_START;
	
	printf("Do you want to create a Linked List: Enter 1 for YES 2 for NO:\n");
    scanf("%d", &d);
	
	if(1==d)
	{
		while(more)
		{
			printf("\nEnter a number:");
			scanf("%d", &data);
			if(NULL == head)
			{
				head=(dubLinkList *)calloc(1, sizeof(struct dubLinkList));
				head->next=NULL;
				head->data=data;
				head->prev = NULL;
				temp=head;
				printf("Head of the Linked List created\n");
			}
			else
			{
				temp->next=(dubLinkList *)calloc(1, sizeof(struct dubLinkList));
				temp->next->data=data;
				temp->next->next=NULL;
				temp->next->prev = temp;
				temp=temp->next;
			}

			printf("\nDo you want to enter one more number: Enter 1 for YES 2 for NO:");
			scanf("%d", &a);
			if(1 == a)
				more=1;
			else
				more=0;
		}
		printf("\nPrinting the contents of List\n");
		printList(head);
		more=1;
		while(more)
		{
			printf("\n Enter one of the following choices \n 1. For Adding a number at the Head  \
  														  \n 2. For adding a number after another Number \
				                                          \n 3. For Adding a number at the Last \
														  \n 4. Deleting the head of list      \
														  \n 5. Deleting a number from the List \
														  \n 6. Deleting the last number from the List \
														  \n 7. Print the contents of the list \
														  \n 8. For REVERSING the Linked List \n:");
			scanf("%d", &d);
			switch(d)
			{
			case 1:
				pos=LIST_START;
				addNode(&head, pos);
				printList(head);
				break;
			case 2:
				pos=LIST_AFTER_A_NUM;
				addNode(&head, pos);
				printList(head);
				break;
			case 3:
				pos=LIST_END;
				addNode(&head, pos);
				printList(head);
				break;
			case 4:
				pos=LIST_START;
				delNode(&head, pos);
				if(NULL != head)
				{
					printf("\nThe resulting linked list is ");
					printList(head);
				}
				else
					printf("\nThe resulting linked list is EMPTY");
				break;
			case 5:
				pos=LIST_AFTER_A_NUM;
				delNode(&head, pos);
				if(NULL != head)
				{
					printf("\nThe resulting linked list is ");
					printList(head);
				}
				else
					printf("\nThe resulting linked list is EMPTY");
				break;
			case 6:
				pos=LIST_END;
				delNode(&head, pos);
				if(NULL != head)
				{
					printf("\nThe resulting linked list is ");
					printList(head);
				}
				else
					printf("\nThe resulting linked list is EMPTY");
				break;
			case 7:
				printList(head);
				break;
			case 8:
				//reverseList(&head);
				printf("\nThe resulting linked list is ");
				printList(head);
				break;
			default:
				printf("\n You have not entered a valid choice \n");
				break;
			}
			printf("\nDo you want to do one more operation: Enter 1 for YES 2 for NO:");
			scanf("%d", &a);
			if(2 == a)
				more=0;
			else
				more=1;
		}

		/* Free the linked list before exiting from the program */
		if(head)
			freeList(&head);
	}
	getche();
}
コード例 #8
0
ファイル: shell.c プロジェクト: spjps2009/cs211
/*parse command to linked list and send to exec function*/
void parse_command(){
	int EXIT;
	int i=0,j,d;
	int test = 0;
	int length = strlen(buffer);
	int count = 1;
	int start = 0;
	int temp = 0;
	int currarg = 0;

	struct Node* head = malloc(sizeof(struct Node));
	memset(head->args,0,sizeof(int) * 50);
	head->next = NULL;
	struct Node* ptr = head;

	for(i = 0; i < length; i++){
		char c = buffer[i];
		if(currarg >= 50){
			fprintf(stderr,"Too many arguements\n");
			test = 2;
			break;
		}
		if(!temp){
			if(c == '|'){
				count++;
				currarg = 0;
				ptr->next = malloc(sizeof(struct Node));
				ptr = ptr->next;
				memset(ptr->args,0,sizeof(int) * 50);
				ptr->next = NULL;
			}else if(c == '\''){
				temp = 1;
				start = i;
			}else if(c == '\"'){
				temp = 2;
				start = i;
			}else if(c != ' ' && c!= '\t'){
				temp = 3;
				start = i;
			}
		}else if((temp == 1 && c == '\'') || (temp == 2 && c == '\"')){
			temp = 0;
			ptr->args[currarg] = malloc(sizeof(char) * (i - start + 2));
			memcpy(ptr->args[currarg],buffer + sizeof(char) * (start + 1), sizeof(char) * ((i - 1) - start));
			ptr->args[currarg][(i - 1) - start] = '\0';
			currarg++;
		}else if(temp == 3 && (c == ' ' || i == length - 1)){
			temp = 0;
			ptr->args[currarg] = malloc(sizeof(char) * (i - start + 2));
			memcpy(ptr->args[currarg],buffer + sizeof(char) * start, sizeof(char) * (i - start));
			ptr->args[currarg][i - start] = '\0';
			currarg++;
		}else if(temp == 3 && c == '|'){
			temp = 0;
			ptr->args[currarg] = malloc(sizeof(char) * (i - start + 2));
			memcpy(ptr->args[currarg],buffer + sizeof(char) * start, sizeof(char) * (i - start));
			ptr->args[currarg][i - start] = '\0';
			count++;
			currarg = 0;
			ptr->next = malloc(sizeof(struct Node));
			ptr = ptr->next;
			memset(ptr->args,0,sizeof(int) * 50);
			ptr->next = NULL;
		}else if(c == '\'' || c == '\"'){
			fprintf(stderr,"error: quote mismatch\n");
			test = 1;
			break;
		}
	}
	/*send to cd function*/
	if(!strcmp(head->args[0], "cd")){
		exec_cd(2, head->args);
		freeList(head);
		return;
	}
	/*send to exit function*/
	if(!strcmp(head->args[0], "exit")){
		exec_exit(2, head->args);
		freeList(head);
		return;
	}
	if(!test && (temp == 1 || temp == 2)){
		fprintf(stderr,"error: quote mismatch\n");
		test = 1;
	}
	if(head->args[0] == NULL){
		test = 1;
	}

	if(!test){
		exec_command(head, -1);
		int status;
		int pid;
		while((pid = wait(&status)) != -1)
			printf("process %i exits with %i\n",pid,status);

	}

	freeList(head);
}
コード例 #9
0
ファイル: GraphTest.c プロジェクト: ssmcgrat/UCSC-coursework
int main(int argc, char* argv[]){
   int order = 8;	//the number of nodes in our Graph G
   Graph G = newGraph(order);
   List S = newList();

   //insert numbers into List S
   for(int i=1; i<=8; i++){
      append(S, i);
   }
   
   printf("Here is our Graph G when first initialized\n");
   printGraph(stdout, G);
   printf("Here is our List S\n");
   printList(stdout, S);
   printf("\n\n");


   //calling addArc() to assign edges to our Graph G
   addArc(G, 1, 2);
   addArc(G, 2, 3);
   addArc(G, 3, 4);
   addArc(G, 4, 3);
   addArc(G, 4, 8);
   addArc(G, 8, 8);
   addArc(G, 7, 8);
   addArc(G, 3, 7);
   addArc(G, 7, 6);
   addArc(G, 6, 7);
   addArc(G, 2, 6);
   addArc(G, 5, 6);
   addArc(G, 5, 1);
   addArc(G, 2, 5); 

   printf("Here is the adjacency list representation of G after adding our directed edges\n");
   printGraph(stdout, G);
   printf("\n");
   
   //Test that transpose() works properly
   Graph T = transpose(G);
   printf("Here is the transpose of G:\n");
   printGraph(stdout, T);

   printf("The order of G is: %d\n", getOrder(G));
   printf("The size of G is: %d\n", getSize(G));
   printf("The parent of node 2 is: %d\n", getParent(G, 2));
   printf("The discover time of node 2 is: %d\n", getDiscover(G, 2));
   printf("The finish tim of node 2 is: %d\n\n\n", getFinish(G, 2));

   DFS(G,S);

   printf("Here is our List S after running DFS():\n");
   printList(stdout, S);
   printf("\n");   
   //Test that discover time, finish time, and parent fields correct after call to DFS()
   for(int i = 1; i<=order; i++){
      printf("Node %d: discovery time = %d ; finish time = %d ; parent = %d\n", 
               i, getDiscover(G, i), getFinish(G, i), getParent(G, i));
   }

   //Test that copyGraph() works properly
   Graph C = copyGraph(G);
   printf("Here is the copy of G:\n");
   printGraph(stdout, C);
   for(int i = 1; i<=order; i++){
      printf("Node %d: discovery time = %d ; finish time = %d ; parent = %d\n", 
               i, getDiscover(C, i), getFinish(C, i), getParent(C, i));
   }

   freeList(&S);
   freeGraph(&G);
   freeGraph(&T);
   freeGraph(&C);
   return(0);
}
コード例 #10
0
ファイル: hexcurse.c プロジェクト: Kerrigan29a/hexcurse
int main(int argc, char *argv[])			/* main program       */
{

    int   x, retval = 1;			/* counters, etc.     */
    off_t val, len;					/* len need to be off_t*/

    windows = (WINS *) calloc(1, sizeof(WINS));	/* malloc windows     */
    head = llalloc();							/* malloc list space  */
    fpINfilename = NULL;			/* allocate in and    */
    fpOUTfilename = NULL;			/* out file name ptrs */
    printHex = TRUE;							/* address format     */
    USE_EBCDIC = FALSE;							/*use ascii by default*/

							/* get cmd line args  */
    len = parseArgs(argc, argv);
    MIN_ADDR_LENGTH = getMinimumAddressLength(len);

    use_env(TRUE);					/* use env values     */
    slk_init(0);					/* init menu bar      */
    init_screen();					/* init visuals       */
    init_colors();

    if ((COLS < MIN_COLS) || (LINES < MIN_LINES))	/* screen's too small */
    {
	endwin();
	fprintf(stderr,"\n\nThe screen size too small.\nThe minimum allowable");
	fprintf(stderr," screen size is %dx%d\n\n", MIN_COLS, MIN_LINES + 1);
	exit(-1);
    }
    
    slk_set(6, (printHex) ? "Hex Addr":"Dec Addr", 1);
    init_fkeys();					/* define menu bar    */
    

    while (retval)
    {
	free_windows(windows);
        
	/* calculate screen   */
	BASE                = (resize > 0 && resize < COLS) ? resize:((COLS-6-MIN_ADDR_LENGTH)/4);
	MAXY                = (LINES) - 3;
	hex_win_width       = BASE * 3;
	ascii_win_width     = BASE;
	hex_outline_width   = (BASE * 3) + 3 + MIN_ADDR_LENGTH;
	ascii_outline_width = BASE + 2;
            
	init_menu(windows);				/* init windows       */
	head = freeList(head);				/* free & init head   */
							/* print origin loc   */
	mvwprintw(windows->hex_outline, 0, 1, "%0*d", MIN_ADDR_LENGTH, 0);
    
	if (fpIN != NULL)				/* if no infile...    */
	{
            len = maxLoc(fpIN);				/* get last file loc  */
	    val = maxLines(len); 			/* max file lines     */
            for (x = 0; x <= MAXY && x<=val; x++)       /* output lines       */
		outline(fpIN, x);
	}

	wmove(windows->hex, 0, 0);			/* cursor to origin   */
    
	refreshall(windows);				/* refresh all wins   */
	doupdate();					/* update screen      */
        
	mvwaddch(windows->scrollbar, 1, 0, ACS_CKBOARD);/* clear scroller     */
							/* get user input     */
	retval = wacceptch(windows, len); 
    }
    
    free(fpINfilename);
    free(fpOUTfilename);
    freeList(head);
    
    screen_exit(0);					/* end visualizations */
    return retval;					/* return             */
}
コード例 #11
0
ファイル: list.c プロジェクト: riclas/rstm
/* =============================================================================
 * list_free
 * =============================================================================
 */
void
list_free (list_t* listPtr)
{
    freeList(listPtr->head.nextPtr);
    SEQ_FREE(listPtr);
}
コード例 #12
0
/*Main------------------------------------------------------------------------*/
int main(int argc, char* argv[]) {
   
    //input validation
   if(argc < 3 || argc > 3) {
       
      //usage message
      printf("Usage: %s [input file] [output_file]\n", argv[0]);
      exit(EXIT_FAILURE);
   }
   
   //the number of lines in the file
   int lineCount = 0;
   char line[MAX_SIZE];
   
   //set the String words
   char words[lineCount][MAX_SIZE];

   //open files for input read and output write
   FILE *in = fopen(argv[1], "r");
   FILE *out = fopen(argv[2], "w");

   //checking input write file pointer
   if(in == NULL ) {
      printf("Unable to open file %s for reading\n", argv[1]);
      exit(EXIT_FAILURE);
   }
   
   //checking output write file pointer
   if(out == NULL ) {
      printf("Unable to open file %s for writing\n", argv[2]);
      exit(EXIT_FAILURE);
   }

   //this will determine the size the string words
   while (fgets(line, MAX_SIZE, in) != NULL) {
      lineCount++;
   }
   
   //this will allow the file pointer to be at the beginning
   fclose(in);
   in = fopen(argv[1], "r");
 
   //reset lineCount to walk through the words and copy the pointers
   lineCount = 0;
   
   //copy pointers to string words
   while(fgets(line, MAX_SIZE, in) != NULL) {
      int iter;
      for (iter = 0; iter < strlen(line); iter++) {
         
         //chop the newline
         if (line[iter] == '\n') {
            words[lineCount][iter] = '\0';
            break;
         }
         words[lineCount][iter] = line[iter];
      }
      lineCount++;
   }

   //Declare a list object and initialize it with a 0
   List list = newList();
   append(list,0);

   //InsertSort walk through each item and place in correct spot
   int iter;
   for (iter = 1; iter < lineCount; iter++) {
      
      //words that are at the front and back of the list
      char *curr_word = words[iter];
      char *front_word = words[front(list)];
      char *back_word = words[back(list)];

      // if the word should be at the front of the list
      if (strcmp(curr_word, front_word) < 0) {
         prepend(list,iter);
      }
      
      //if the word should be at the end of the list
      else if (strcmp(curr_word, back_word) > 0) {
         append(list,iter);
      }
      
      //if the word belongs within the list
      else {
          
         //start the beginning of the list and work each word lexicographically
         moveTo(list,0);
         
         //compare each word until you find the correct spot and stop the loop
         while (strcmp(curr_word, words[getElement(list)]) > 0) {
            moveNext(list);
         }
         
         //when stopped this is the correct index so insert here
         insertBefore(list, iter);
      }
   }

   //output the words to the file
   for (moveTo(list,0); getIndex(list)>= 0; moveNext(list)) {
      fprintf(out,"%s\n", words[getElement(list)]);
   }

   //free all nodes in the list
   freeList(&list);
   
   //close the input read and output write files
   fclose(in);
   fclose(out);

   return(EXIT_SUCCESS);
}
コード例 #13
0
ファイル: stack.c プロジェクト: bvisness/whitespace
void freeStack(Stack* stack) {
    freeList(stack->pList);
    free(stack);
}
コード例 #14
0
ファイル: unadf.c プロジェクト: NF6X/ADFlib
int main(int argc, char* argv[])
{
    int i, j;
    BOOL rflag, lflag, xflag, cflag, vflag, sflag, dflag, pflag, qflag;
    struct List* files, *rtfiles;
    char *devname, *dirname;
    char strbuf[80];
    unsigned char *extbuf;
    int vInd, dInd, fInd, aInd;
    BOOL nextArg;

    struct Device *dev;
    struct Volume *vol;
    struct List *list, *cell;
    int volNum;
    BOOL true = TRUE;

    if (argc<2) {
        help();
        exit(0);
    }

    rflag = lflag = cflag = vflag = sflag = dflag = pflag = qflag = FALSE;
    vInd = dInd = fInd = aInd = -1;
    xflag = TRUE;
    dirname = NULL;
    devname = NULL;
    files = rtfiles = NULL;
    volNum = 0;

    fprintf(stderr,"unADF v%s : a unzip like for .ADF files, powered by ADFlib (v%s - %s)\n\n",
        UNADF_VERSION, adfGetVersionNumber(),adfGetVersionDate());

    /* parse options */
    i=1;
    while(i<argc) {
        if (argv[i][0]=='-') {
            j=1;
            nextArg = FALSE;
            while(j<(int)strlen(argv[i]) && !nextArg) {
                switch(argv[i][j]) {
                case 'v':
                    vflag = TRUE;
                    if ((i+1)<(argc-1)) {
                        i++;
                        nextArg = TRUE;
                        errno = 0;
                        volNum = atoi(argv[i]);
                        if (errno!=0 || volNum<0) {
                            fprintf(stderr,"invalid volume number, aborting.\n");
                            exit(1);
                        }
                    }
                    else
                        fprintf(stderr,"no volume number, -v option ignored.\n");
                    break;
                case 'l': 
                    lflag = TRUE;
                    xflag = FALSE;
                    break;
                case 's': 
                    sflag = TRUE;
                    break;
                case 'c': 
                    cflag = TRUE;
                    break;
                case 'r':
                    rflag = TRUE;
                    break;
                case 'd':
                    if (devname!=NULL && xflag && (i+1)==(argc-1)) {
                        i++;
                        dirname = argv[i];
                        if (dirname[strlen(dirname)-1]==DIRSEP)
                            dirname[strlen(dirname)-1]='\0';
                        nextArg = TRUE;
                        dflag = TRUE;
                    }
                    break;
                case 'p':
                    if (xflag) {
                        fprintf(stderr,"sending files to pipe.\n");
                        pflag = TRUE;
                        qflag = TRUE;
                    }
                    else
                        fprintf(stderr,"-p option must be used with extraction, ignored.\n");
                    break;
                case 'h':
                default:
                    help();
                    exit(0);
                } /* switch */
            j++;
            } /* while */
        } /* if */
        else {
			/* the last non option string is taken as a filename */
            if (devname==NULL) /* if the device name has been already given */
                devname = argv[i];
            else {
                if (xflag) {
                    if (rtfiles==NULL)
                        rtfiles = files = newCell(NULL, (void*)argv[i]);
                    else
                        files = newCell(files, (void*)argv[i]);
                }
                else
                    fprintf(stderr,"Must be used with extraction, ignored.\n");
            }
        }
        i++;
    } /* while */

    extbuf =(unsigned char*)malloc(EXTBUFL*sizeof(char));
    if (!extbuf) { fprintf(stderr,"malloc error\n"); exit(1); }

    /* initialize the library */
    adfEnvInitDefault();

    dev = adfMountDev( devname,TRUE );
    if (!dev) {
        sprintf(strbuf,"Can't mount the dump device '%s'.\n", devname);
        fprintf(stderr, strbuf);
        adfEnvCleanUp(); exit(1);
    }
    if (!qflag)
        printDev(dev);

    if (volNum>=dev->nVol) {
        fprintf(stderr,"This device has only %d volume(s), aborting.\n",dev->nVol);
        exit(1);
    }

    vol = adfMount(dev, volNum, TRUE);
    if (!vol) {
        adfUnMountDev(dev);
        fprintf(stderr, "Can't mount the volume\n");
        adfEnvCleanUp(); exit(1);
    }

    if (!qflag) {
        printVol(vol, volNum);
        putchar('\n');
    }

    if (cflag && isDIRCACHE(vol->dosType) && lflag) {
        adfChgEnvProp(PR_USEDIRC,&true);
        if (!qflag)
            puts("Using dir cache blocks.");
    }

    if (lflag) {
        if (!rflag) {
            cell = list = adfGetDirEnt(vol,vol->curDirPtr);
            while(cell) {
                printEnt(vol,cell->content,"", sflag);
                cell = cell->next;
            }
            adfFreeDirList(list);
        } else {
            cell = list = adfGetRDirEnt(vol,vol->curDirPtr,TRUE);
            printTree(vol,cell,"", sflag);
            adfFreeDirList(list);
        }
    }else if (xflag) {
        if (rtfiles!=NULL) {
            files = rtfiles;
            while(files!=NULL) {
                if (dirname!=NULL)
                    processFile(vol, (char*)files->content, dirname, extbuf, pflag, qflag);
                else
                    processFile(vol, (char*)files->content, "", extbuf, pflag, qflag);
                files = files->next;
            }
            freeList(rtfiles);
        }
        else {
            cell = list = adfGetRDirEnt(vol,vol->curDirPtr,TRUE);
            if (dirname==NULL)
                extractTree(vol, cell, "", extbuf, pflag, qflag);
            else
                extractTree(vol, cell, dirname, extbuf, pflag, qflag);
            adfFreeDirList(list);
        }
    }
    else
        help();

    free(extbuf);

    adfUnMount(vol);
    adfUnMountDev(dev);

    adfEnvCleanUp();

    return(0);
}
int main(int argc, char* argv[]){
	Graph G = newGraph(11);

//int i = 0; 

addEdge(G, 1, 4);
addEdge(G, 1, 6);
addEdge(G, 3, 4);
addEdge(G, 4, 7);
addEdge(G, 2, 1);
addEdge(G, 2, 4);
addEdge(G, 5, 6);
addEdge(G, 6, 2);
addEdge(G, 8, 9);
addEdge(G, 8, 1);
addEdge(G, 6, 3);
addEdge(G, 5, 7);
addEdge(G, 9, 10);
addEdge(G, 10, 3);


printGraph(stdout, G);
//output
//4 6 2 8
//1 4 6 
//4 6 10 
//1 3 7 2 
//6 7 
//1 5 2 3 
//4 5 
//9 1 
//8 10 
//9 3

//Run BFS
BFS(G, 4);
//New List to check getPath
List L = newList();
getPath(L, G, 9);
//clear and run BFS on source
clear(L);
BFS(G, 4);
//get path on BFS
getPath(L, G, 4);
clear(L);
getPath(L, G, 11);

//Test if BFS ran correctly
//get Vertices
fprintf(stdout, "%d\n", getOrder(G));
//get Size
fprintf(stdout, "%d\n", getSize(G));
//get Source
fprintf(stdout, "%d\n", getSource(G));
//get Parent of 10
fprintf(stdout, "%d\n", getParent(G, 10));
//getParent of 4
fprintf(stdout, "%d\n", getParent(G, 4));
//get Distance from 10 to source(4);
fprintf(stdout, "%d\n", getDist(G, 10));
//get Distance from 4 to source(itself);
fprintf(stdout, "%d\n", getDist(G, 4));

makeNull(G);
freeList(&L);
freeGraph(&G); 
}
コード例 #16
0
ファイル: queues.c プロジェクト: adijkema/algo
/* Function for .... 
 */
void freeQueue (Queue q) {
	freeList(q.list);
}
コード例 #17
0
ファイル: ralcalc.c プロジェクト: ralight/ralcalc
/*
 * processLine()
 *
 * Take a string, tokenise it, validate it and pass it on for calculation. This
 * is the glue function of ralcalc really.
 */
int processLine(const char *line, int quiet, displayMode dm, char siPrefix, int precision)
{
	tokenItem tokenList;
	int rc;
	FILE *rcptr;
	double result;
	double lastResult = 0.0;
	int hasError = 0;
	char resultStr[100];
	char formatStr[20];

	if(!line) return errBadInput;

	if(rcpath){
		rcptr = fopen(rcpath, "rb");
		if(rcptr){
			rc = fread(&lastResult, sizeof(double), 1, rcptr);
			if(rc != 1){
				fprintf(stderr, "Warning: Previous value file corrupt, ignoring.\n");
				lastResult = 0.0;
			}
			fclose(rcptr);
		}
	}

	/* First element always defined and not dynamic for less hassle */
	tokenList.next = NULL;
	tokenList.type = tkEndToken;

	rc = tokenise(&tokenList, line, lastResult, quiet);
	if(rc != errNoError) hasError = 1;

	rc = validate(&tokenList, line, quiet);
	if(rc != errNoError) hasError = 1;

	rc = assignPrecedence(&tokenList);
	if(rc != errNoError) hasError = 1;

	if(!hasError && tokenList.next){
		result = process(&(tokenList.next));

		switch(dm){
			case dmSI:
				doubleToString(result, resultStr, 100, siPrefix, precision);
				break;
			case dmExponent:
				if(precision == -1){
					snprintf(resultStr, 100, "%lg", result);
				}else{
					snprintf(formatStr, 20, "%%.%dlg", precision);
					snprintf(resultStr, 100, formatStr, result);
				}
				break;
			case dmRaw:
				if(precision == -1){
					snprintf(resultStr, 100, "%f", result);
				}else{
					snprintf(formatStr, 20, "%%.%df", precision);
					snprintf(resultStr, 100, formatStr, result);
				}
				break;
		}

		if(!quiet){
			printf("%s = %s\n", line, resultStr);
		}else{
			printf("%s\n", resultStr);
		}

		if(rcpath){
			rcptr = fopen(rcpath, "wb");
			if(rcptr){
				rc = fwrite(&result, sizeof(double), 1, rcptr);
				if(rc != 1){
					fprintf(stderr, "Error writing last value file.\n");
				}
				fclose(rcptr);
			}
		}
	}

	if(tokenList.next) freeList(tokenList.next);

	return hasError;
}
コード例 #18
0
ファイル: nss_pcache.c プロジェクト: shawnwhit/httpd_modnss
int main(int argc, char ** argv)
{
    SECStatus rv;
    PRFileDesc *in;
    PRFileDesc *out;
    PRPollDesc pd;
    PRIntervalTime timeout = PR_INTERVAL_NO_TIMEOUT;
    char buf[1024];
    PRInt32 nBytes;
    char * command;
    char * tokenName;
    char * tokenpw;
    int fipsmode = 0;
    int semid = 0;
    union semun semarg;

    if (argc < 4 || argc > 5) {
        fprintf(stderr, "Usage: nss_pcache <semid> <fips on/off> <directory> [prefix]\n");
        exit(1);
    }

    signal(SIGHUP, SIG_IGN);

    semid = strtol(argv[1], NULL, 10);

    if (!strcasecmp(argv[2], "on"))
        fipsmode = 1;

    /* Initialize NSPR */
    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 256);
 
    /* Set the PKCS #11 strings for the internal token. */
    PK11_ConfigurePKCS11(NULL,NULL,NULL, INTERNAL_TOKEN_NAME, NULL, NULL,NULL,NULL,8,1);
 
    /* Initialize NSS and open the certificate database read-only. */
    rv = NSS_Initialize(argv[3], argc == 5 ? argv[4] : NULL, argc == 5 ? argv[4] : NULL, "secmod.db", NSS_INIT_READONLY);

    if (rv != SECSuccess) {
        fprintf(stderr, "Unable to initialize NSS database: %d\n", rv);
        exit(1);
    }

    if (fipsmode) {
        if (!PK11_IsFIPS()) {
            char * internal_name = PR_smprintf("%s",
                SECMOD_GetInternalModule()->commonName);

            if ((SECMOD_DeleteInternalModule(internal_name) != SECSuccess) ||
                 !PK11_IsFIPS()) {
                 NSS_Shutdown();
                 fprintf(stderr,
                     "Unable to enable FIPS mode");
                 exit(1);
            }
            PR_smprintf_free(internal_name);
        } 
    }

    in = PR_GetSpecialFD(PR_StandardInput);
    out = PR_GetSpecialFD(PR_StandardOutput);
    if (in == NULL || out == NULL) {
        fprintf(stderr, "PR_GetInheritedFD failed\n"); 
        exit(1);
    }

    pd.fd = in;
    pd.in_flags = PR_POLL_READ | PR_POLL_EXCEPT;
    while (1) {
        rv = PR_Poll(&pd, 1, timeout);
        if (rv == -1) { /* PR_Poll failed */
            break;
        }
        if (pd.out_flags & (PR_POLL_HUP | PR_POLL_ERR | PR_POLL_NVAL | PR_POLL_EXCEPT)) {
            break;
        }
        if (pd.out_flags & PR_POLL_READ) {
            memset(buf, 0, sizeof(buf));
            nBytes = PR_Read(in, buf, sizeof(buf));
            if (nBytes == -1 || nBytes == 0) {
                break;
            }
            command = getstr(buf, 0);
            tokenName = getstr(buf, 1);
            tokenpw = getstr(buf, 2);

            if (command && !strcmp(command, "QUIT")) {
                break;
            } else if (command && !strcmp(command, "STOR")) {
                PRInt32 err = PIN_SUCCESS;
                Node *node = NULL;

                if (tokenName && tokenpw) {
                    node = (Node*)malloc(sizeof (Node));
                    if (!node) { err = PIN_NOMEMORY; }

                    node->tokenName = strdup(tokenName);
                    node->store = 0; 
                    node->next = 0; 

                    if (err == PIN_SUCCESS)
                        err = CreatePk11PinStore(&node->store, tokenName, tokenpw);
                    memset(tokenpw, 0, strlen(tokenpw));
                } else
                    err = PIN_SYSTEMERROR;

                sprintf(buf, "%d", err);
                PR_Write(out, buf, 1);

                if (err == PIN_SUCCESS) {
                    if (pinList)
                        node->next = pinList;
                    pinList = node;
                }

                /* Now clean things up */
                if (command) free(command);
                if (tokenName) free(tokenName);
                if (tokenpw) free(tokenpw);
            } else if (command && !strcmp(command, "RETR")) {
                Node *node;
                char *pin = 0;
                PRBool found = PR_FALSE;

                for (node = pinList; node != NULL; node = node->next) {
                    if (!strcmp(node->tokenName, tokenName)) {
                        if (Pk11StoreGetPin(&pin, node->store) == SECSuccess) {
                            if (strlen(pin) == 0)
                                PR_Write(out, "", 1);
                            else
                                PR_Write(out, pin, strlen(pin));
                            memset(pin, 0, strlen(pin));
                            free(pin);
                            found = PR_TRUE;
                            break;
                        }
                    }
                }

                if (found != PR_TRUE)
                    PR_Write(out, "", 1);

                free(command);
                free(tokenName);
            } else {
              ; /* ack, unknown command */
            }
        }
    }
    freeList(pinList);
    PR_Close(in);
    /* Remove the semaphore used for locking here. This is because this
     * program only goes away when Apache shuts down so we don't have to
     * worry about reloads.
     */
    semctl(semid, 0, IPC_RMID, semarg);
    return 0;
}
コード例 #19
0
//
// main: runs a simple test to check the hashList functions
//
void main(int argc, char* argv[]){
	//First create log file to log output
	FILE *log;
	log = open_log("hashListText.log");
	Log(log, " ---- Testing HashList Functions ---- \n");

	//Declare a new hashList
	Log(log, " ---- Test 1: newHashList() ---- \n");
	hashList *list = newHashList();

	if (list == NULL)
		Log(log, "   Error: creating newHashList\n");
	else{
		Log(log, "   Success: Created newHashList\n");
		Log(log, "   size of list: %d\n", list->size);
	}

	//create chunk hashes for adding to hashList
	char ch1[HASHSIZE], ch2[HASHSIZE], ch3[HASHSIZE];
	char *t1 = "ac2972d828a1c1af10401368a136f5a27b1e592c";
	char *t2 = "a727b711e4f2986fbe9e3add54a0ec3bc015ddc9";
	char *t3 = "2d448a28ea58e6f884a31c7666b55189a37f40a1";

	Log(log, " ---- Test 2: hexCharsToBinary ---- \n");

	if (hexCharsToBinary(t1, ch1, sizeof(t1)) == 1)
		Log(log, "   Created chunkHash ch1: %x\n", ch1);
	else
		Log(log, "   Error: creating chunkHash ch1\n");
	
	if (hexCharsToBinary(t2, ch2, sizeof(t2)) == 1)
		Log(log, "   Created chunkHash ch2: %x\n", ch2);
	else
		Log(log, "   Error: creating chunkHash ch2\n");

	if(hexCharsToBinary(t3, ch3, sizeof(t3)) == 1)
		Log(log, "   Created chunkHash ch3: %x\n", ch3);
	else
		Log(log, "   Error: creating chunkHash ch3\n");
	
	//Create the hashNodes
	Log(log, " ---- Test 3: newHashNode ---- \n");
	hashNode *node1 = newHashNode(ch1, 0);
	hashNode *node2 = newHashNode(ch2, 1);
	hashNode *node3 = newHashNode(ch3, 0);

	if (node1 != NULL)
		Log(log, "   Created new hashNode 1\n");
	if (node2 != NULL)
		Log(log, "   Created new hashNode 2\n");
	if (node3 != NULL)
		Log(log, "   Created new hashNode 3\n");
	
	//Add the nodes to the hashList
	Log(log, " ---- Test 4: appendNode ---- \n");
	appendNode(list, node1);
	if (list->size == 1)
		Log(log, "   Appended node1, size of list: %d\n", list->size);

	appendNode(list, node2);
	if(list->size == 2)
		Log(log, "   Appended node2, size of list: %d\n", list->size);
	
	//Look for the nodes in the hashList
	Log(log, " ---- Test 5: findHashNode ---- \n");
	if(node1 == findHashNode(list, ch1))
		Log(log, "   Found hashNode in list: node1\n");
	if(node2 == findHashNode(list, ch2))
		Log(log, "   Found hashNode in list: node2\n");
	if(node3 != findHashNode(list, ch2))
		Log(log, "   Did not find node3 in list. Correctly returned NULL\n");

	//remove a node from the hashList
	Log(log, " ---- Test 6: removeNode ---- \n");
	Log(log, "   size of list: %d\n", list->size);
	removeNode(list, node2);
    Log(log, "   Removed hashNode from list: node2\n");


	if(node2 != findHashNode(list, ch2)){
		Log(log, "   size of list: %d\n", list->size);
	}
	if(removeNode(list, node2) == FAILURE){
		Log(log, "   Good. Cannot remove node that doesn't exist in list: node2\n");
		Log(log, "   size of list: %d\n", list->size);
	}
	removeNode(list, node1);
    Log(log, "   Removed hashNode from list: node1\n");

	if(node1 != findHashNode(list, ch1)){
		Log(log, "   size of list: %d\n", list->size);
	}

	if(removeNode(list, node3) == FAILURE){
		Log(log, "   Good. Cannot remove node that doesn't exist in list: node3\n");
		Log(log, "   size of list: %d\n", list->size);
	}
	if(removeNode(list, node1) == FAILURE){
		Log(log, "   Good. Cannot remove node that doesn't exist in list: node1\n");
		Log(log, "   size of list: %d\n", list->size);
	}

	Log(log, " ---- Test 7: freeNode ---- \n");
	if(freeNode(node1) == SUCCESS)
		Log(log, "   Freed: node1\n");
	if(freeNode(node2) == SUCCESS)
		Log(log, "   Freed: node2\n");

	Log(log, " ---- Test 8: freeList ---- \n");
	if(freeList(list) == SUCCESS)
		Log(log, "   Freed Empty List: list\n");

	Log(log, "   Creating new list with node3.\n");
	hashList *list2 = newHashList();
	appendNode(list2, node3);
	appendNode(list2, node3);

	Log(log, "   Size of list: %d\n", list2->size);
	if(freeList(list2) == FAILURE)
		Log(log, "   FAILED to free list with nodes: list2\n");
	else
		Log(log, "   Freed list with nodes: list2\n");


/* The following functions from hashList should ideally also be tested.
 * However, until we can identify a problem to be within one of these functions
 * prior to testing, they will be assumed to be working, because thus far,
 * they are and are not causing any problems.
 *
	Log(log, " -- Test 9: findAddrNode -- \n");
	Log(log, " -- Test 10: getChunkID -- \n");
	Log(log, " -- Test 11: getNextHashFromFile -- \n");
	Log(log, " -- Test 12: putTimeout -- \n");
	Log(log, " -- Test 13: putAddr -- \n");
*/

}
コード例 #20
0
ファイル: FindComponents.c プロジェクト: ddsun95/projects
int main (int argc, char** argv) {
   if (argc != 3) {
      printf ("usage: FindComponents infile outfile\n");
      exit (1);
   }
   int lines = 0;
   char buf[MAXLINE];
   FILE* count = fopen (argv[1], "r");
   FILE* read  = fopen (argv[1], "r");
   FILE* out   = fopen (argv[2], "w");
   if (count == NULL || read == NULL) {
      printf ("Unable to open %s for reading\n", argv[1]);
      exit (1);
   }
   if (out == NULL) {
      printf ("Unable to open %s for writing", argv[2]);
      exit (1);
   }
   while (fgets (buf, MAXLINE, count) != NULL) ++lines;
   char** linebuf = malloc (sizeof (char*) * lines);
   for (int i = 0; i < lines; ++i) {
      char line[MAXLINE];
      fgets (line, MAXLINE, read);
      linebuf[i] = malloc (sizeof (line) + 1);
      strcpy (linebuf[i], line);
      strtok (linebuf[i], "\n");
   }
   Graph dfsg = newGraph (atoi (linebuf[0]));
   process (dfsg, linebuf);
   Graph tran = transpose (dfsg);
   List vertlist = newList();
   for (int i = 1; i <= getOrder (dfsg); ++i) append (vertlist, i);
   DFS (dfsg, vertlist);
   DFS (tran, vertlist);

   int strong = 0, strong_;
   for (int i = 1; i <= getOrder (tran); ++i)
      if (getParent (tran, i) == NIL) ++strong;
   strong_ = strong;
   List comps[strong];
   fprintf (out, "Adjacency list representation of G:\n");
   printGraph (out, dfsg);
   fprintf (out, "\n");
   fprintf (out, "G contains %d strongly connected components:\n", strong);
   for (int i = 0; i < strong; ++i) comps[i] = newList();
   for (moveFront (vertlist); index (vertlist) >= 0; moveNext (vertlist)) {
      if (getParent (tran, get (vertlist)) == NIL) --strong;
      append (comps[strong], get (vertlist));
   }
   for (int i = 1; i <= strong_; i++) {
      fprintf (out, "Component %d: ", i);
      printList (out, comps[i - 1]);
      fprintf (out, "\n");
   }
   for (int i = 0; i < strong_; i++) freeList (&comps[i]);
   for (int i = 0; i < lines; i++) free (linebuf[i]);
   free (linebuf);
   freeGraph (&dfsg);
   freeGraph (&tran);
   freeList (&vertlist);
   fclose (out);
   fclose (read);
   fclose (count);
   return EXIT_SUCCESS;
}
コード例 #21
0
ファイル: Lex.c プロジェクト: UVERkill/CMPS101
int main(int argc, char * argv[]) {
	if(argc != 3) {
		printf("Usage: %s <input file> <output file>\n", argv[0]);
		exit(1);
	}

	FILE *in, *out;	

	// read input with fopen "r"
	in = fopen(argv[1], "r");
	// write to output with fopen "w"
	out = fopen(argv[2], "w");
	if(in == NULL) {
		printf("Unable to open file %s for reading\n", argv[1]);
		exit(1);
	}
	if(out == NULL) {
		printf("Unable to open file %s for writing\n", argv[2]);
		exit(1);
	}

	// Count number of lines in file and then reopen file
	char line[MAX_LEN];
	int lines = 0;
	while(fgets(line, MAX_LEN, in) != NULL) {
		lines++;
	}

	fclose(in);
	in = fopen(argv[1], "r");

	// Initialize the word array
	// Read the words into an array while allocating memory for each
	// word from the input file
	int n = 0;
	char **words = (char **)malloc(lines * sizeof(char*));
	char* word;
	while(fgets(line, MAX_LEN, in) != NULL) {
		word = malloc((strlen(line)+1) * sizeof(char));
		strcpy(word, line);
		words[n++] = word;
		free(word);
	}

	// Insertion Sort to alphabetize file
	List sorted = newList();
	append(sorted, 0);
	char* current;
	int j;
	int flag;
	// Insertion Sort on the String array of words into List
	for(int i=1; i<lines; i++) {
		flag = 0;
		current = words[i];
		moveTo(sorted, 0);
		j = 0;
		while(!flag && j<i) {
			printf("%s", current);
			if(strcmp(current, words[getElement(sorted)])<0) {
				insertBefore(sorted, i);
				flag = 1;
			} else {
				moveNext(sorted);
				j++;
			}
		}
		if(!flag) {
			append(sorted, i);
		}
	}

	// Print words alphabetically to output file
	for(int i=0; i<lines; i++) {
		moveTo(sorted, i);
		fprintf(out, "%s", words[getElement(sorted)]);
	}

	// free memory
	free(words);
	freeList(&sorted);

	// close files
	fclose(in);
	fclose(out);

	return(0);
}
コード例 #22
0
ファイル: snp.c プロジェクト: DiogoRFerreira/RCI
int main(int argc, char * argv[]){
	//Pointer to
    element * ptr_to_first=NULL;
    //Integers to check the arguments
    int i,j,bad_arguments=0, contagem=0;
    //Port variables
    int snp_port = 0,porto_servidor = 0;
    //IP variables, Surname, Message
    char * ip_servidor = (char*)malloc(20*sizeof(char));
    char * ip_maquina = (char*)malloc(20*sizeof(char));
    char * surname = (char*)malloc(30*sizeof(char));
    char * name_ip_servidor = (char*)malloc(126*sizeof(char));
    char * message = (char*)malloc(126*sizeof(char));
	//Addresses
    struct in_addr ipaddress, ipaddress_sa;
    //Check the application's arguments
    if(argc==7){//saip and saport omitted, argc=7 (snp -n surname -s snpip -q snpport)
        for(i=1;i<7;i+=2){
            if(strcmp(argv[i],"-n")==0){//Surname
                if(strlen(argv[i+1])>20){//Check the lenght of the surname
                    printf("Invalid Surname: Too big...\n");
                    bad_arguments=1;
                }else{
                    if(argv[i+1][0]>'Z'|| argv[i+1][0]<'A'){//First letter must be a capital
                        printf("Invalid Surname: Must use a capital letter for the first character of a surname\n");
                        bad_arguments=1;
                    }else{
                        for(j=1;j<=(strlen(argv[i+1])-1);j++){//Must be lower case
                            if('a'>argv[i+1][j] || argv[i+1][j]>'z'){
                                printf("Invalid Surname: Must use lower case letters to the rest of the surname \n");
                                bad_arguments=1;
                            }
                        }
                        strncpy(surname, argv[i+1],strlen(argv[i+1]));
						printf("%s\n",surname);
                        contagem++;
                    }
                }
            }else if(strcmp(argv[i],"-s")==0){//IP address
                if(inet_pton(AF_INET,argv[i+1],&(ipaddress.s_addr))==1){//Check if the ip is valid
                    strcpy(ip_maquina, argv[i+1]);
                    contagem++;
                }else{
                    printf("Invalid IP Address\n");
                }
            }else if(strcmp(argv[i],"-q")==0){//UDP Port, Port value must be between 1024 and 65535 (maxvalue is 65535 2^16-1 16 bits)  1024–49151 registed ports 49151-65535 are called dynamic and/or private ports
                if((49151 < atoi(argv[i+1])) && (atoi(argv[i+1])<= 65535)){//Check if the port is valid
                    snp_port=atoi(argv[i+1]);
                    contagem++;
                }else{
                    printf("Invalid Port: Value of Port must be between 49151 and 65535\n");
                    bad_arguments=1;
                }
            }
        }
        //Get the address of Tejo
        strcpy(name_ip_servidor,"tejo.tecnico.ulisboa.pt");//Omitted values
        ipaddress_sa = getaddressbyname(&name_ip_servidor);//Convert from name to ip - gethostsname.c
        porto_servidor = 58000;
        if(contagem != 3){bad_arguments=1;}//Wrong arguments

    //All arguments, argc=11
    }else if(argc==11){
        for(i=1;i<11;i+=2){
            if(strcmp(argv[i],"-n")==0){//Surname
                if(strlen(argv[i+1])>20){//Check the lenght of the surname
                    printf("Invalid Surname: Too big...\n");
                    bad_arguments=1;
                }else{
                    if(argv[i+1][0]>'Z'|| argv[i+1][0]<'A'){//First letter must be a capital
                        printf("Invalid Surname: Must use a capital letter for the first character of a surname\n");
                        bad_arguments=1;
                    }else{
                        for(j=1;j<=(strlen(argv[i+1])-1);j++){//Must be lower case
                            if('a'>argv[i+1][j] || argv[i+1][j]>'z'){
                                printf("Invalid Surname: Must use lower case letters to the rest of the surname \n");
                                bad_arguments=1;
                            }
                        }
                        strncpy(surname, argv[i+1],strlen(argv[i+1]));
                        contagem++;
                    }
                }
            }else if(strcmp(argv[i],"-s")==0){//IP address SNP
                if(inet_pton(AF_INET,argv[i+1],&(ipaddress.s_addr))==1){//Check if the ip is valid
                    strcpy(ip_maquina, argv[i+1]);
                    contagem++;
                }else{
                    printf("Invalid IP Address\n");
                }
            }else if(strcmp(argv[i],"-q")==0){//UDP Port SNP
                if((49151 < atoi(argv[i+1])) && (atoi(argv[i+1])<= 65535)){//Check if the port is valid
                    snp_port=atoi(argv[i+1]);
                    contagem++;
                }else{
                    printf("Invalid Port: Value of Port must be between 49151 and 65535\n");
                    bad_arguments=1;
                }
            }else if(strcmp(argv[i],"-i")==0){//IP address SA
                if(inet_pton(AF_INET,argv[i+1],&(ipaddress_sa.s_addr))==1){//Check if the ip is valid
                    strcpy(ip_servidor, argv[i+1]);
                    contagem++;
                }else{
                    printf("Invalid IP Address\n");
                }
            }else if(strcmp(argv[i],"-p")==0){//Port SA
                if((49151 < atoi(argv[i+1])) && (atoi(argv[i+1])<= 65535)){//Check if the port is valid
                    porto_servidor=atoi(argv[i+1]);
                    contagem++;
                }else{
                    printf("Invalid Port: Value of Port must be between 49151 and 65535\n");
                    bad_arguments=1;
                }
            }
        }
        if(contagem != 5){bad_arguments=1;}//Wrong arguments
    }

    //Missing arguments , too many arguments or bad arguments
    if((argc!=7 && argc!=11) || bad_arguments == 1){
        printf("Start the program as follows: ./snp -n surname -s snpip -q snpport [-i saip] [-p saport]\n");
        exit(-1);
    }
    //Values
    printf("SNP:\nSurname: %s\nIP address: %s\nPort: %d\n\n",surname,ip_maquina,snp_port);
    printf("SA:\nIP address: %s\nPort: %d\n\n",inet_ntoa(ipaddress_sa),porto_servidor);

    //-----------------------------------Menu------------------------------------------------//
    struct sockaddr_in addr;
    int fd_file,fd_socket_schat, num_elements=0, exit_menu=0;
    int *num_elements_ptr= &num_elements;
    fd_set readset;
    char option[32];
    
    printf("\nWelcome to the Name Server Interface. Choose an action: \n\n 1: list\n 2: exit \n");
	//------Open socket to communicate with Schat's------
    if((fd_socket_schat = socket(AF_INET,SOCK_DGRAM,0))==-1){
		perror("Socket: "); exit(1);
	}
    memset((void*)&addr,(int)'\0',sizeof(addr));
    addr.sin_family=AF_INET;
    addr.sin_addr.s_addr=htonl(INADDR_ANY);
    addr.sin_port=htons(snp_port);
    //Bind
    if(bind(fd_socket_schat,(struct sockaddr*)&addr,sizeof(addr))==-1){
		perror("Bind failed: "); exit(2);
	}
	//----------------------------------------------
    //Regist of the SNP on SA
    sprintf(message,"SREG %s;%s;%d",surname,ip_maquina,snp_port);
    udp_socket(ipaddress_sa,porto_servidor,&message);//udp_socket_client.c
	printf("Registed on SA. Waiting for connections ...\n");
	//----------------------------------------------
	//Main cycle: waiting for activity on socket or input from keyboard
    while(exit_menu==0){
        fd_file = fileno(stdin);
        FD_ZERO(&readset);
        FD_SET(fd_socket_schat,&readset);
        FD_SET(fileno(stdin), &readset);
        if(select(max(fd_file,fd_socket_schat)+1,&readset,NULL,NULL,NULL)==-1){
			perror("Error in select(): ");  exit(3); //Error in select
		}
		//Activity on keyboard
        if(FD_ISSET(fd_file,&readset)) {
            fgets(option,32,stdin);
            if (strncmp(option,"exit",4)==0){
                printf("Server terminating...\n");
                exit_menu=1;
            }else{
                if(strncmp(option,"list",4)==0){
                    printf("List: [%d]\n", num_elements);
                    printList(ptr_to_first);
                }else {
                    printf("Command not found.\n");
                }
            }
        } 
		// Activity on socket
        if(FD_ISSET(fd_socket_schat,&readset)) {
            ptr_to_first = udp_socket_server(ptr_to_first,num_elements_ptr, fd_socket_schat,addr,ipaddress_sa);//udp_socket_client.c
        }
	}
	//---------------------------------------------------------------------------------//
    //------Remove SNP from SA-----//
    sprintf(message,"SUNR %s",surname);
    udp_socket(ipaddress_sa,porto_servidor,&message);//udp_socket_client.c
    //Frees
    free(message); free(name_ip_servidor); free(surname); free(ip_servidor); free(ip_maquina);
    freeList(ptr_to_first);
	//Exit
    exit(0);
}
コード例 #23
0
ファイル: pagerank.c プロジェクト: hihellohi/cs1927ass2
int main(int argc, char **argv){

	//check usage
	if(argc != 4){
		fprintf(stderr, "usage: \"./pagerank\" damping_factor diffPR maxIterations");
		return EXIT_FAILURE;
	}

	//initialise i/o
	FILE *fin = fopen("collection.txt","r");
	FILE *fout = fopen("pagerankList.txt","w");
	double d, diffPR;
	int maxIterations;
	slist urls = newList((void*)strdup, free);
	d = atof(argv[1]);
	diffPR = atof(argv[2]);
	maxIterations = atoi(argv[3]);

	//read collection.txt
	char buffer[BUFF_SIZE];
	while(fscanf(fin, "%s", buffer) != EOF){
		assert(buffer[0]);
		listEnter(urls, buffer);
	}
	
	int len = listLength(urls);
	Url *aurls = malloc(len * sizeof(url));
	Graph g = newGraph(len);
	Hashmap m = newHashmap((len*3)/2);
	
	//convert llist to array for faster reading
	int i;
	for(i = 0; i < len; i++){
		aurls[i] = malloc(sizeof(url));
		aurls[i]->name = (char*)readList(urls);
		aurls[i]->pRank = (1/(double)len);
		aurls[i]->notActuallyZero = 1;
		mapInsert(m, aurls[i]->name, i);
		listNext(urls);
	}
	listReset(urls);

	//build graph
	for(i = 0; i < len; i++){
		strcpy(buffer, aurls[i]->name);
		strcat(buffer, ".txt");
		FILE *webpage = fopen(buffer, "r");
		char *seen = calloc(len, sizeof(char));
		int nOutgoingLinks = 0;

		fscanf(webpage, "#start Section-1");
		while (fscanf(webpage, "%s", buffer) != EOF){
			if(!strcmp(buffer, "#end")){
				break;
			}

			int j = mapSearch(m, buffer);
			if(j != -1 && j != i && !seen[j]){
				insertEdge(g,j,i);
				seen[j] = 1;
				nOutgoingLinks++;
			}
		}

		if(!nOutgoingLinks){
			int j;
			for(j = 0; j < len; j++){
				if(j != i) {
					insertEdge(g, j, i);
				}
			}
			nOutgoingLinks = len - 1;
			aurls[i]->notActuallyZero = 0;
		}
		aurls[i]->outdeg = nOutgoingLinks;
		fclose(webpage);
		free(seen);
	}
	
	dropMap(m);

	//calculate pagerank
	double diff = diffPR, *newPRanks = malloc(len * sizeof(double));
	for(i = 0; i < maxIterations && diff > diffPR - EPS; i++){
		diff = 0;
		
		int j;
		for(j = 0; j < len; j++){
			double sum = 0;

			slist inUrls;
			for(inUrls = GetAdjacencies(g, j); hasNext(inUrls); listNext(inUrls)){
				int val = *(int*)readList(inUrls);
				sum += aurls[val]->pRank / aurls[val]->outdeg;
			}
			listReset(inUrls);

			sum *= d;
			sum += (1 - d)/len;
			diff += fabs(aurls[j]->pRank - sum);
			newPRanks[j] = sum;
		}
		for(j = 0; j < len; j++) {
			aurls[j]->pRank = newPRanks[j];
		}
	}
	free(newPRanks);			

	mergesort((void**)aurls, len, urlComp, 1);
	print(aurls, fout, len);
	
	for(i = 0; i < len; i++){
		free(aurls[i]);
	}

	free(aurls);
	fclose(fin);
	fclose(fout);
	freeList(urls);
	dropGraph(g);
	return EXIT_SUCCESS;
}
コード例 #24
0
Events::~Events(void) {
	debug(8, "Shutting down event subsystem...");
	freeList();
}
コード例 #25
0
int main(int argc, char * argv[]){
   int count=0;
   //int check = 0;
   int u, v;
   FILE *in, *out;
   char line[MAX_LEN];
   char* token;
   Graph G;
   List path = newList();

   // check command line for correct number of arguments
   if( argc != 3 ){
      printf("Usage: %s <input file> <output file>\n", argv[0]);
      exit(1);
   }

   // open files for reading and writing 
   in = fopen(argv[1], "r");
   out = fopen(argv[2], "w");
   if( in==NULL ){
      printf("Unable to open file %s for reading\n", argv[1]);
      exit(1);
   }
   if( out==NULL ){
      printf("Unable to open file %s for writing\n", argv[2]);
      exit(1);
   }

   /* read each line of input file, then count and print tokens */
   while(fgets(line, MAX_LEN, in) != NULL)  {
      count++;
	  // char *strtok(char *str, const char *delim) breaks string str into
	  // a series of tokens using the delimitrer delim. This function returns a pointer to the
	  // last token found in string. A null pointer is returned if there are no tokens left to retrieve.
      token = strtok(line, " \n");
	  
	  // int atoi(const char *str), This function returns the converted integral number as an int value.
	  // If no valid conversion could be performed, it returns zero.
	  // It converts char to int.
	  if(count == 1) {
	     // Takes in the first number as a token, sets a graph of that size
	     G = newGraph(atoi(token));
	  }
	  else {
	     // Here we want to read in both numbers
		 u = atoi(token);
		 token = strtok(NULL, " \n");
		 v = atoi(token);
		 if( u != 0 || v != 0) {
		       addEdge(G, u, v);
	     }		   
         else if (u == 0 && v == 0) {
		       //check = 1;
         }			   
      } 
   }
   printGraph(out, G);
   

   while( fgets(line, MAX_LEN, in) != NULL)  {
	  token = strtok(line, " \n");
      u = atoi(token);
      token = strtok(NULL, " \n");
	  v = atoi(token);
	  if( u != NIL) {
		 BFS(G, u);
	     clear(path);
		 getPath(path, G, v);
		 if(u != NIL ) {
		    fprintf(out, "The distance from %d to %d is %d\n", getSource(G), v, getDist(G, v));
			fprintf(out, "A shortest %d-%d path is: ", getSource(G), v);
			printList(out, path);
			fprintf(out, "\n");
		 }
	     else {
			fprintf(out, "There is no %d-%d path", getSource(G), v);
			fprintf(out, "\n");
	     }
      }
   }
	  
   freeGraph(&G);	
   freeList(&path);

   /* close files */
   fclose(in);
   fclose(out);

   return(0);
}
コード例 #26
0
ファイル: AddressBook.c プロジェクト: timothyong/systems
void deleteBook(node ** book){
  int i;
  for (i = 0; i < 26; i++){
    freeList(*(book+i));
  }
}
コード例 #27
0
ファイル: Bio_square.c プロジェクト: bmountjoy/LMTools
float * getPointsFromFiles
(
	char ** files,
	int     numFiles,
	double  centroidEasting,
	double  centroidNorthing,
	int     sideLength,
	float   zThreshold,
	int *   numZ,
	int *   numAll
)
{
	printf("getPointsFromFiles: numfiles %d \n", numFiles);
	
	*numZ   = 0;
	*numAll = 0;
	
	Node * head = NULL;
	int    i;
	
	for(i = 0; i < numFiles; i++)
	{
		printf("\t%d %s\n", i, files[i]);
		FILE * file;
		
		if(!(file = fopen(files[i], "rb")))
		{
			continue;
		}
		getPointsFromFileSquare(file, &head, centroidEasting, centroidNorthing, sideLength, zThreshold, numZ, numAll);
		printf("\tnumz:%d\n",*numZ);
		printf("\tnuma:%d\n",*numAll);
		//printf("\thead->value:%f",head->value);
		//printf("\textractPoints : %d %d %f\n", *numZ, *numAll, head->value);
		
		fclose(file);
	}
	
	/**
	 * Copy list to a float array.
	 */
	 
	float * zValues;
	
	if((zValues = initFloatBuffer1D(*numZ, -999.0)) == NULL)
	{
		return NULL;
	}
	
	Node * curr;
	
	curr = head;
	i = 0;
	
	puts("About to free the list");
	
	while(curr)
	{
		zValues[i++] = curr->value;
		curr = curr->next;
	}
	freeList(head);
	
	return zValues;
}
コード例 #28
0
ファイル: lab2.c プロジェクト: justinmccaffrey/From-Classes
//Deletes all nodes in the list
void freeList(struct node * head){
    if(head->next!=NULL){
        freeList(head->next);
    }
    free(head);
}
コード例 #29
0
ファイル: list.c プロジェクト: nmldiegues/proteustm
/* =============================================================================
 * list_free
 * =============================================================================
 */
void
list_free (list_t* listPtr)
{
    freeList(listPtr->head.nextPtr);
    free(listPtr);
}
コード例 #30
0
ファイル: client.c プロジェクト: suhussai/Process-Manager
int main(int argc, char * argv[]) {
  
  killOldProcNannies();
  debugPrint("staring main\n");
  if (pipe(newProcessToChild) < 0) {
    fprintf(stderr,"pipe error");
    exit(0);
  }

  if (pipe(killCountPipe) < 0) {
    fprintf(stderr,"pipe error");
    exit(0);
  }

  fcntl(killCountPipe[0], F_SETFL, O_NONBLOCK);

  debugPrint("connecting to %s on port %d \n", argv[1], atoi(argv[2]));
  MY_PORT = atoi(argv[2]);
	
  /* Put here the name of the sun on which the server is executed */
  host = gethostbyname (argv[1]);


  int firstTime = 1;
  if (host == NULL) {
    perror ("Client: cannot get host description");
    exit (1);
  }

  s = socket (AF_INET, SOCK_STREAM, 0);

  if (s < 0) {
    perror ("Client: cannot open socket");
    exit (1);
  }

  bzero (&server, sizeof (server));
  bcopy (host->h_addr, & (server.sin_addr), host->h_length);
  server.sin_family = host->h_addrtype;
  server.sin_port = htons (MY_PORT);

  while (connect (s, (struct sockaddr*) & server, sizeof (server))) {
    perror ("Client: cannot connect to server");
    debugPrint("Tring again\n");
    //exit (1);
  }




  char * pipeBuffer = NULL;
  /* char * procInfoRequest = malloc(200); */
  /* snprintf(procInfoRequest,200, "%-200s", procInfoString); */
  /* char * a = "test\0"; */
  char a[200] = "test";
  char * processName = NULL;
  int len = 0;
  int numberofProcesses = 0;
  int processLifeSpan = 0;
  int PID = 0;
  char * pointerToProcessName = NULL;
  char * pointerToPipeBuffer = NULL;


  while (keepLooping == 1) {
    // use this loop to get process lists

    pipeBuffer = malloc(63);
    pointerToPipeBuffer = pipeBuffer;

    debugPrint("writing server\n");
    writeToServer(a);
    readFromServer(pipeBuffer);
    debugPrint("got %s\n", pipeBuffer);
    
    if (pipeBuffer[0] == '!') {
      keepLooping = 0;
      debugPrint("got exit signal!!!!!\n");
      continue;
    }

    //    char * tmpBuffer = pipeBuffer;
  
    //    char * processName;
    len = 0;
    numberofProcesses = 0;
    processLifeSpan = 0;
    PID = 0;

    len = strchr(pipeBuffer,'#') - pipeBuffer;
    processName = malloc(len+1);
    pointerToProcessName = processName;
    strncpy(processName, pipeBuffer, len);
    processName[len] = '\0'; 

    processName[strlen(processName) - 1] = '\0';

  
    pipeBuffer = strchr(pipeBuffer,'#');
    numberofProcesses = atoi(pipeBuffer+1);
    processLifeSpan = atoi(strchr(pipeBuffer,'!')+1);
    debugPrint("server: we have  %d different procs to monitor\n", numberofProcesses);

    if (processLifeSpan == 99) {
      // 99 is the code indicating that the 
      // server received a sighup
      // so flush our linked list record
      // of processes

      free(pointerToPipeBuffer);
      free(pointerToProcessName);
      pipeBuffer = NULL;
      processName = NULL;




      if (processList) {
	freeList(processList); // free it in case it is still set
	processList = NULL;
      }



      pipeBuffer = malloc(63);
      pointerToPipeBuffer = pipeBuffer;

      //      debugPrint("writing server\n");
      //      writeToServer(a); // we likely dont need to write test again cuz 
                                // our initial message should still be there
      readFromServer(pipeBuffer);
      debugPrint("got %s\n", pipeBuffer);
    
      if (pipeBuffer[0] == '!') {
	keepLooping = 0;
	debugPrint("got exit signal!!!!!\n");
	continue;
      }

      //    char * tmpBuffer = pipeBuffer;
  
      //    char * processName;
      len = 0;
      numberofProcesses = 0;
      processLifeSpan = 0;
      PID = 0;

      len = strchr(pipeBuffer,'#') - pipeBuffer;
      processName = malloc(len+1);
      pointerToProcessName = processName;
      strncpy(processName, pipeBuffer, len);
      processName[len] = '\0'; 

      processName[strlen(processName) - 1] = '\0';

  
      pipeBuffer = strchr(pipeBuffer,'#');
      numberofProcesses = atoi(pipeBuffer+1);
      processLifeSpan = atoi(strchr(pipeBuffer,'!')+1);
      debugPrint("server: we have  %d different procs to monitor\n", numberofProcesses);



    }

    free(pointerToPipeBuffer);
    free(pointerToProcessName);
    pipeBuffer = NULL;
    processName = NULL;
    //    free(processName);
    while(numberofProcesses > 0) {
      //      char * processName = NULL;
      len = 0;
      processLifeSpan = 0;
      PID = 0;
      numberofProcesses--;

      pipeBuffer = malloc(63);
      pointerToPipeBuffer = pipeBuffer;
      readFromServer(pipeBuffer);
      

      len = strchr(pipeBuffer,'#') - pipeBuffer;
      processName = malloc(len+1);
      pointerToProcessName = processName;
      //processName = (char *)realloc(processName, len+1);
      strncpy(processName, pipeBuffer, len);
      processName[len] = '\0'; 

      processName[strlen(processName) - 1] = '\0';

  
      pipeBuffer = strchr(pipeBuffer,'#');
      PID = atoi(pipeBuffer+1);
      processLifeSpan = atoi(strchr(pipeBuffer,'!')+1);


      char *newP = trimwhitespace(processName);

      debugPrint("for PID = %d\n", PID);
      debugPrint("name: %s \n", newP);
      debugPrint("life span: %d \n", processLifeSpan);
      debugPrint("pid: %d \n", PID);
      //      close (s);
      debugPrint("Process %d got %s\n", getpid (),
	       pipeBuffer);

      if (processList) { 
	if ( searchNodes(processList, newP, processLifeSpan) == -1) {
	  debugPrint("%d adding node \n", getpid());
	  addNode(processList, newP, processLifeSpan);	  
	}
      }
      else {
	debugPrint("creating process list... %d processListing node \n", getpid());
	processList = init(newP, processLifeSpan);
      }

      debugPrint("finished setting/looking thro processList\n");
      free(pointerToPipeBuffer);
      free(pointerToProcessName);
      pipeBuffer = NULL;
      processName = NULL;
    }


    sleep (5);
    updateKillCount();
    debugPrint("********************\n");

    debugPrint("number of freechildren is %d: \n", freeChildren);
    debugPrint("number of messages from children is %d: \n", messagesFromChildren);
    struct node * cursorNode;
    int i = 0;
    debugPrint("processes we monitored are: \n");
    cursorNode = monitoredPIDs;
    if (monitoredPIDs) {
      for (i = 0; i < getSize(monitoredPIDs); i++) {
	debugPrint("value: %s, key: %d\n", cursorNode->value, cursorNode->key);
	cursorNode = cursorNode->next;
      }
      
    }


    debugPrint("process we got are: \n");

    cursorNode = processList;

    for (i = 0; i < getSize(processList); i++) {
      debugPrint("for %s, %d \n",cursorNode->value, cursorNode->key);

      if (getNumberOfPIDsForProcess(cursorNode->value) > 0 || firstTime == 1) {
	debugPrint("calling monitorProcess \n");
	monitorProcess(cursorNode->value, cursorNode->key);   	
      }
      else {
	debugPrint("NOT calling monitorProcess \n");
	debugPrint("No %s proc found.\n", cursorNode->value);
      }

      cursorNode = cursorNode->next;
    }
    firstTime = 0;
    debugPrint("done listing processes in processList\n");


      
      
  }
  
  free(pipeBuffer);
  //  free(processName);
  
  freeList(processList);
  freeList(monitoredPIDs);
  freeList(childPIDs);
  return 0;
}