Pages

Subscribe:

Ads 468x60px

Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Wednesday, January 23, 2013

Producer Consumer Problem in C++

Today I'm going to solve a most common problem which is known as the consumer producer problem. In this context we have a shared buffer which the producers produce and the consumers consume. The consumers and producers are threads which will simultaneously produce and consume. There are some conditions to be met where consumers have to wait until producers produce, and another thing is that when the buffer is full producers must halt until the consumers consume.

In the following example was implemented using pthreads. The producer produce a random number to the buffer and consumers consume that number. Mutex locks are used to protect the shared buffer. 
ProducerConsumer.cpp     DOWNLOAD SOURCE

#include <iostream>
#include <pthread.h>
#include <vector>
#include <cstdlib>
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>



#define BUFFER_SIZE 10

void InitializeData();
void *Produce(void *);
void *Consume(void *);
int InsertItem(int);
int RemoveItem(int *);

int iCounter;
pthread_mutex_t mutex;
sem_t full, empty;

int buffer[BUFFER_SIZE];



int main(int argc , char * argv[])
{
 InitializeData(); 
 pthread_t ProducerThread , ConsumerThread;
 int *aa = new int [10];
 for(int i = 0 ; i < 10 ; i++)
 {
  aa[i] = i;
  pthread_t t;
  pthread_create(&t , NULL, Produce , &aa[i]);
  printf("Creating Producer %d \n", i);
 }
 int *bb = new int[10];
 for(int i = 0 ; i < 10 ; i++)
 {
  bb[i] = i;
  pthread_t t;
  pthread_create(&t , NULL, Consume , &bb[i]);
  printf("Creating Consumer %d \n", i);
 }
 
 sleep(5);
 delete [] aa;
 delete [] bb;
 

 return 0;
}

//****************************************************************************************************
void InitializeData()
{
 pthread_mutex_init(&mutex , NULL);
 sem_init(&full , 0 ,0);
 sem_init(&empty , 0 , BUFFER_SIZE);
 
 iCounter = 0;
 

}

//****************************************************************************************************
void * Produce(void * Param)
{
 int item;
 
 while(1)
 {
  //sleep(1);
  item = rand() % 100;
  sem_wait(&empty);
  pthread_mutex_lock(&mutex);
  int iMsg = InsertItem(item);
  
  if(iMsg == -1){
   printf("Error Inserting Item \n");
  }else
  {
   printf("Produced Item :: %d  Thread No :: %d\n", item , *((int *)Param));
  }
  pthread_mutex_unlock(&mutex);
  sem_post(&full);
  
 }
}

//****************************************************************************************************
void * Consume(void * Param)
{
 int item;
 
 while(1)
 {
  //sleep(1);
  sem_wait(&full);
  pthread_mutex_lock(&mutex);
  int iMsg = RemoveItem(&item);
  
  if(iMsg == -1){
   printf("Error Removing Item \n");
  }else
  {
   printf("Consumed Item :: %d  Thread No :: %d \n", item ,*((int *)Param));
  }
  pthread_mutex_unlock(&mutex);
  sem_post(&empty);
  
 }
}

//****************************************************************************************************
int InsertItem(int item)
{
 if(iCounter < BUFFER_SIZE)
 {
  buffer[iCounter] =  item;
  iCounter++;
  return 1;
 }
 else{
  return -1;
 }

}

//****************************************************************************************************
int RemoveItem(int *item)
{
 if(iCounter > 0)
 {
  *item = buffer[iCounter - 1];
  iCounter--;
  return 1;
 }
 else{
  return -1;
 }
}

That's it folks. Hope to see you soon in another exciting tutorial.

Friday, January 18, 2013

How to send Complex Data Structures in a Socket Program

Hi all, Hope you guys are doing well. I was busy with my work last few days. Today I'm going to write a post about sending Complex data structures using a socket program. In this post I assume that you are somewhat familiar with the socket programming basics.

In the following example we are creating a Object type in the server program and send that to the client program. This is a simple serialize and deserialize mechanism to send complex data structures through a socket program using only the STL library. If you want more complex and complete functionality you might try the boost library. 

Here we are going to send the following data structure.
 Data.h File
class InnerData{
    public:
    int c;
};

class Data{
    public:
    int a;
    char b[20];
    InnerData id;
  
};

Now we write the Server program which will create a socket, bind that socket to a port and listen for incoming connections. If there is a incoming connection accept the connection, serialize the data send to the connected client.

Server.cpp File
#include <stdio.h>
#include <cstdlib> 
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include <arpa/inet.h> 
#include "Data.h"

int main(int argc , char * argv [])
{
    int SockFD , NewSockFD , PortNo, Clilen;
    char Buffer[1024];
 struct sockaddr_in Server_Addr , Cli_Addr;
 int n , pID;

 //create a socket
 SockFD =  socket(AF_INET , SOCK_STREAM , 0);
 if(SockFD < 0)
 {
  perror("Error Creating Socket \n");
  exit(1);
 }
 std::cout << "Socket Created..." << std::endl;

 bzero((char *) &Server_Addr , sizeof(Server_Addr));
 PortNo = atoi(argv[1]);
 Server_Addr.sin_family = AF_INET;
 Server_Addr.sin_addr.s_addr = INADDR_ANY;
 Server_Addr.sin_port = htons(PortNo);

 
 //bind the socket
 if(bind(SockFD , (struct sockaddr *) &Server_Addr , sizeof(Server_Addr)) < 0)
 {
  perror("Error Binding \n");
  exit(1);
 }
 std::cout << "Socket Binded..." << std::endl;
 //listen for incoming clients
 listen(SockFD , 5);
 Clilen =  sizeof(Cli_Addr);
 std::cout << "Waiting For Connections..." << std::endl;
 
 while(1)
 {
  //accept a client 
  NewSockFD = accept(SockFD , (struct sockaddr *) &Cli_Addr ,(socklen_t *) &Clilen);
  printf("New Client %d \n", NewSockFD);
  if(NewSockFD < 0)
  {
   perror("Error accepting \n");
   exit(1);
  }  
   bzero(Buffer , 1024);
   printf("New Client Connected, Process ID :: %d \n",pID);
   //create the Data
   Data *data = new Data();
   data->a = 23232;
   strcpy(data->b , "TEST MESSAGE" );
   data->id.c =1000;
  
   n =  write(NewSockFD , data ,sizeof(*data) );
   if(n < 0)
   {
    perror(" Error Sending Message \n");
    exit(1);
   }
  
 }
 return 0;
}

Now the client accept the data send by the client and deserialize it.

Client.cpp
#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h> 
#include "Data.h"


int main(int argc , char * argv [])
{
 int SockFD , PortNo , n;
 struct sockaddr_in Server_Address;
 struct hostent *Server;
 
 char Buffer[1024]; // Buffer to read data

 if(argc < 3)
 {
  printf("Error hostname port required \n");
  exit(0);
 }
 PortNo = atoi(argv[2]);
 // create a socket 
 SockFD =  socket(AF_INET , SOCK_STREAM , 0);

 if(SockFD < 0 )
 {
  perror("Error Creating Socket");
  exit(1);
 }
 
 Server = (struct hostent *) gethostbyname(argv[1]);
 if(Server == NULL)
 {
  printf("Error :: No Such Host \n");
  exit(0);
 }

 bzero((char *) &Server_Address , sizeof(Server_Address));
 Server_Address.sin_family =  AF_INET;
 bcopy((char *) Server->h_addr , (char *) &Server_Address.sin_addr.s_addr , Server->h_length);
 
 Server_Address.sin_port = htons(PortNo);
 
 //connect to the server
 if(connect(SockFD , (struct sockaddr *) &Server_Address , sizeof(Server_Address)) < 0)
 {
  perror("Error Connecting \n");
  exit(1);
 }
 Data * data = new Data();
 n = read(SockFD , Buffer , sizeof(Data));
 data = (Data *) Buffer;
 printf("Read Size %d \n" , n);
 if(n < 0)
 {
  perror("Error receiving data \n");
  exit(1);
 }
 printf("Received :: ID :: %d  MESSAGE :: %s Complex ID:: %d \n", data->a , data->b ,data->id.c );
 bzero(Buffer , 1024);

 return 0;

}

First we compile the Server.cpp file
g++ -o Server Server.cpp

Then we run the server giving the port as an argument.
./Server  7788

Then compile and run the client program using a new terminal.
g++ -o Client Client.cpp

./Client localhost 7788

That's it folks. It's a simple approach. But solve the problem. Remember that this only works since we are using the same computer architecture. If you are using different architectures you have to consider about the endian problem also.. :)

Monday, December 24, 2012

fatal error LNK1168: cannot open 'filename.exe' for writing

Hi guys how you all doing?.. I have just finished my University work and having a free week before joining the Industry. Recently I was trying to do some projects using Microsoft Visual C++ 2010 Express in Windows 8 Operating System environment. When I tried to build few solutions I came with the Error called

fatal error LNK1168: cannot open 'filename.exe' for writing

Recently I have disabled some windows services since Some features were slowing down my laptop. Then I realized that I have disabled the Application Experience Service also. 

If you experience the same error go to Start >> Run >> services.msc

Then start the Application Experince Service. That's it. It will solve the error.
 

Friday, November 30, 2012

How to write a Simple Web Server using C

In this post I'm going to explain how to write a simple but functional web server using sockets. First we have to set configuration for our web server and most common way of doing is to put the configurations into a .ini file. I used inih which is a simple .ini parser written in C. source 

Below is a sample .ini file
; Config file for ASK server

[Protocol]             
Version=6              ; IPv6

[Web]
http_version=HTTP/1.1
root_dir = www/
default_page = index.html
error_page = error.html
backlog = 10
max_header_size=1024

[Codes]
200 = OK
404 = Content Not Found

Below is the  askserver.c source file.  First the configurations are loaded and waiting for incoming requests. Then whenever a request is arrived the server check for the file requested. If it is available send a message code 200 and the file type server is going to send to the client. If the requested file was not fond, then send the message code 400 content not found. 
When a available file is send to the client, method is used.

sendfile(destination, source, offset,size);

//******************** askserver.c ******************/
// Aruna Sujith Karunarathna
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/sendfile.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <netinet/tcp.h>
#include <limits.h>
#include <unistd.h>
#include <assert.h>
#include "ini.h"

#define CONFIGURATION_FILE  "configuration/ask.ini"


typedef struct{
    int version;
    int backlog;
	int max_header_size;
    const char* http_version;
    const char* root_dir;
	const char* default_page;
	const char* error_page;
} configuration;
configuration config;

void sigchld_handler(int s){
	while(waitpid(-1, NULL, WNOHANG) > 0);
}

// get sockaddr, IPv4 or IPv6:
void *get_in_addr(struct sockaddr *sa){
	if (sa->sa_family == AF_INET) {
		return &(((struct sockaddr_in*)sa)->sin_addr);
	}
	return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

static int handler(void* user, const char* section, const char* name,const char* value){
    
    configuration* pconfig = (configuration*)user;

    #define MATCH(s, n) strcasecmp(section, s) == 0 && strcasecmp(name, n) == 0
    if (MATCH("protocol", "version")) {
        pconfig->version = atoi(value);   
    } else if (MATCH("web", "http_version")) {
        pconfig->http_version = strdup(value);
    } else if (MATCH("web", "root_dir")) {
        pconfig->root_dir = strdup(value);
    } else if (MATCH("web", "default_page")) {
        pconfig->default_page = strdup(value);
    } else if (MATCH("web", "error_page")) {
        pconfig->error_page = strdup(value);
    } else if (MATCH("web", "backlog")) {
        pconfig->backlog = atoi(value);
    } else if (MATCH("web", "max_header_size")) {
        pconfig->max_header_size = atoi(value);
    } else {
        return 0;  /* unknown section/name, error */
    }
    return 1;
}

char* get_extension(char* file_name){
    char* extension;
    extension = strchr(file_name,'.')+1	; 
    printf("EXTENSION %s \n",extension);
    return extension;
}

char* get_content_type(char* extension){
    char* type;
    if(strcmp(extension,"html")==0)
        type = "text/html";
    else if(strcmp(extension,"css")==0)
        type = "text/css";
    else if(strcmp(extension,"txt")==0)
        type = "application/text";
    else if(strcmp(extension,"pdf")==0)
        type = "application/pdf";
    else if(strcmp(extension,"zip")==0)
        type = "application/zip";    
    else if(strcmp(extension,"xml")==0)
        type = "application/xml";  
    else if(strcmp(extension,"js")==0)
        type = "application/javascript";                  
    else if(strcmp(extension,"jpg")==0)
        type = "image/jpg";
    else if(strcmp(extension,"png")==0)
        type = "image/png";    
    else if(strcmp(extension,"exe")==0)
        type = "application/octet-stream";
    else if(strcmp(extension,"ico")==0)
        type = "image/x-icon";
    else if(strcmp(extension,"php")==0)
        type = "text/html";
        
    printf("TYPE %s ",type);    
    return type;    

}

int set_header(char *header,int status_code,char *file_name,int file_length){
    if(status_code==404){
        //printf("%s %d File Not Found\n",config.http_version,status_code);
        sprintf(header, 
				"%s %d File Not Found\n"					
		     	 "\n",config.http_version,status_code);
		printf("\nHEADER MESSAGE %s \n",header);
        return -1;
    }
	if(status_code==400){
		sprintf(header, 
				"%s %d Bad Request\n"					
		     	 "\n",config.http_version,status_code);
		return -1;
	}
	if(status_code==501){	
		sprintf(header,"%s %d POST Not Implemented\n "
		"\n POST Not Implemented",config.http_version,status_code);	
		return -1;
	}
	char *extension;
	extension = get_extension(file_name);     
	char *content_type;
	content_type = get_content_type(extension);
		
	sprintf(header,"%s %d OK \n"	
	"Content-Type: %s\n"
	"Content-Length: %i\n"
		      "\n",config.http_version,status_code,content_type ,file_length);
	printf("\nHEADER MESSAGE %s \n",header);	      
}

char* check_request(char * request){
	char* ptr;
	ptr = strstr(request," HTTP/");
   // printf("CHK REQUEST %s \n",request);
	if(ptr == NULL)	{
		printf("Not HTTP request\n");
	}else{
	 /* *** HTTP request received *** */

		/* *** check for GET request *** */
		if(strncmp(request,"GET ",4) == 0)	{
			ptr="GET";
		}
		/* *** check for POST request, give 501 error if received *** */
		else if(strncmp(request,"POST ",5) == 0){
			printf("501 Method not implemented\n");
			ptr="POST";
		}
	}

	return ptr; 
}

char* get_path(char *request)
{
	int i=0;
//	printf("REQUEST %s \n",request);
	char *token = NULL;
	token = strtok(request, " ");
	token = strtok(NULL, " ");
	
	return token;
}

int send_content(char* file_name, int socket, int status_code){
    int sent_size; 	
    char header[config.max_header_size];
	int open_file;               /* file descriptor for source file */
    struct stat stat_buf;  /* hold information about input file */
    off_t offset = 0;      /* byte offset used by sendfile */
    int return_code;                /* return code from sendfile */
  
    open_file = open(file_name, O_RDONLY);/* check that source file exists and can be opened */ 
    fstat(open_file, &stat_buf);         /* get size and permissions of the source file */
   
  
	set_header(header,status_code,file_name,(int)stat_buf.st_size);
	sent_size=send(socket, header, strlen(header), 0);
	
	
    /* copy file using sendfile ####################################### */
    // sendfile(destination, source, offset,size);
    return_code = sendfile (socket, open_file, &offset, stat_buf.st_size);
    printf("file size %d Bytes \n\n",return_code);
    
    if (return_code == -1) {
        fprintf(stderr, "error from sendfile: %s\n", strerror(errno));
 	}
 	else if (return_code != stat_buf.st_size) {
        fprintf(stderr, "incomplete transfer from sendfile: %d of %d bytes\n", return_code, (int)stat_buf.st_size); 
    }
    /* clean up and exit */
    close(socket);
    close(open_file);
    return 0;

}

int main(int argc, char* argv[]){

        if (ini_parse(CONFIGURATION_FILE , handler, &config) < 0) {
                printf("Can't load 'ask.ini'\n");
                return 1;
        }
         printf("Config loaded from 'ask.ini':\nversion=%d\nbacklog=%d\nmax_header_size=%d \nhttp_version=%s\n",
        config.version, config.backlog, config.max_header_size, config.http_version);
        
	int sockfd, new_fd;  // listen on sock_fd, new connection on new_fd
	struct addrinfo hints, *servinfo, *p;
	struct sockaddr_storage their_addr; // connector's address information
	socklen_t sin_size;
	struct sigaction sa;
	int yes=1;
	char s[INET6_ADDRSTRLEN];
	int rv;

	memset(&hints, 0, sizeof hints);
	hints.ai_family = AF_UNSPEC;
	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_PASSIVE; // use my IP

	if ((rv = getaddrinfo(NULL, argv[1], &hints, &servinfo)) != 0) {
		fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		return 1;
	}

	// loop through all the results and bind to the first we can
	for(p = servinfo; p != NULL; p = p->ai_next) {
		if ((sockfd = socket(p->ai_family, p->ai_socktype,
				p->ai_protocol)) == -1) {
			perror("server: socket");
			continue;
		}

		if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes,
				sizeof(int)) == -1) {
			perror("setsockopt");
			exit(1);
		}

		if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
			close(sockfd);
			perror("server: bind");
			continue;
		}

		break;
	}

	if (p == NULL)  {
		fprintf(stderr, "server: failed to bind\n");
		return 2;
	}

	freeaddrinfo(servinfo); // all done with this structure

	if (listen(sockfd, config.backlog) == -1) {
		perror("listen");
		exit(1);
	}

	sa.sa_handler = sigchld_handler; // reap all dead processes
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = SA_RESTART;
	if (sigaction(SIGCHLD, &sa, NULL) == -1) {
		perror("sigaction");
		exit(1);
	}

	printf("ASK_SERVER: waiting for connections...\n");

	while(1) {  // main accept() loop
		sin_size = sizeof their_addr;
		new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
		if (new_fd == -1) {
			perror("accept");
			continue;
		}

		inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr),s, sizeof s);
		printf("ASK_SERVER: got connection from %s\n", s);

		if (!fork()) { // this is the child process
			close(sockfd); // child doesn't need the listener
			int buffer_size =1024;
			char* char_buffer = malloc(buffer_size);
			//get the client request
			read(new_fd,char_buffer,buffer_size);
			char *path;
  		    //printf("REQUEST ------ %s \n",char_buffer);
			//printf("CHECK_REQUEST %s \n",check_request(char_buffer));
			char* request_type = check_request(char_buffer);
			printf("REQUEST TYPE ::::::: %s\n",request_type);
			char* header=malloc(200);
  		    memset(header,0,200);
            
            if(request_type==NULL){	  	
  			    set_header(header,400,NULL,0);
  			    send(new_fd, header, strlen(header), 0);
  			    return 0;
  			}
  		    else if(strcmp(request_type,"POST")==0){
  			    set_header(header,501,NULL,0);
  			    send(new_fd, header, strlen(header), 0);
  			    return 0;
  		    }   
  		    
  		    path = get_path(char_buffer);
  		    if(strcmp("/",path)==0){
  		        path = (char*)config.default_page;
  		        // path = config.default_page;
  		    }
  		    char *root_dir=malloc(100);
			memset(root_dir,0,sizeof root_dir);
			strcpy(root_dir,config.root_dir);			
			path=strcat(root_dir,path);
			//printf("11111111111 real %s \n", path);
			
			/* ******* REQUEST FILE FOUND ********** */
  		    if(access(path, F_OK ) != -1){
				 send_content(path,new_fd,200);
				 //printf("OKKKKKKKKK %s \n", path);
			}
  		    else{					
				memset(root_dir,0,100);
				strcpy(root_dir,config.root_dir);
				path=strcat(root_dir,"/");
				path=strcat(root_dir,config.error_page);
				//printf("ERRRRRRRRRRORRR %s \n",path);
				send_content(path,new_fd,404);	
			}
  		    
			
		//	if (send(new_fd, "Hello, world!", 13, 0) == -1)
		//		perror("send");
		    free(char_buffer);
			close(new_fd);
			exit(0);
		}
		close(new_fd);  // parent doesn't need this
	}	
	
        printf("Config loaded from 'ask.ini': version=%d, backlog=%d,max_header_size=%d ,  http_version=%s\n",
        config.version, config.backlog, config.max_header_size, config.http_version);
        return 0;
		
}

I have included a sample www folder in the same directory to simulate the web server.

Download the full project from here.... DOWNLOAD

How to Test the Sample ASK Server.

Open a Terminal and Type the Following Commands.

[aruna@ubuntu]~$ makefile

[aruna@ubuntu]~$ ./askserver 7788


The argument 7788 is the port that we bind the webserver. Now open a web browser and type the following address localhost:7788

You'll see the web server is up and running. :)

Sunday, August 26, 2012

Longest Path Algorithm (Java Code)

The longest path algorithm is used to find the maximum length of a given graph. The maximum length may be measured by the maximum number of edges or the sum of the weights in a weighted graph. Following is a sample java code to find the Longest Path. It has two classes. CreateMatrix.java class to create the matrix and LongestPath.java to find the Longest Path to the created matrix. 

Download Source From Here.. DOWNLOAD

/********************* LongestPathAlgo.java ********************/ 
class LongestPathAlgo {

    public static void main(String[] args) {

        int length = 13;//length of the 2-D array
        int adjMatrix[][] = new int[length][length];
        CreateMatrix cm = new CreateMatrix();
        cm.createMatrix(length);
        adjMatrix = cm.readMatrix(adjMatrix);

        long starttime = System.nanoTime();
        LongestPathAlgo lpa = new LongestPathAlgo();
        boolean visited[] = new boolean[adjMatrix.length];
        lpa.initialize(adjMatrix, visited);
        int max = lpa.longestPath(0, visited, adjMatrix);
        long runtime = System.nanoTime()-starttime;
        System.out.println("Runtime =" + runtime +" nano seconds");
        System.out.println("Longest Path Length = "+max);
    }

    public void initialize(int adjMatrix[][], boolean visited[]) {
        for (int u = 0; u < adjMatrix.length; u++) {
            visited[u] = false;
        }
    }

    int longestPath(int vertex, boolean visited[], int adjMatrix[][]) {
        int dist, max = 0;
        visited[vertex] = true;

        for (int u = 0; u < adjMatrix[vertex].length; u++) {
            if (adjMatrix[vertex][u] != -1) {
                if (!visited[u]) {
                    dist = adjMatrix[vertex][u] + longestPath(u, visited, adjMatrix);
                    if (dist > max) {
                        max = dist;
                    }
                }
            }
        }
        visited[vertex] = false;
        return max;
    }
}

/********************* CreateMatrix.java ********************/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;


public class CreateMatrix {

    public void createMatrix(int length) {
        Random ran = new Random();
        FileWriter fw;
        try {
            File file = new File("matrix.txt");
            fw = new FileWriter(file);
            BufferedWriter bw = new BufferedWriter(fw);
            for (int i = 0; i < length; i++) {
                for (int j = 0; j < length; j++) {
                    if (i == j) {
                        bw.write("" + -1);
                    } else {
                        bw.write("" + (i+j));
                    }
                    bw.write("@");
                }
                bw.newLine();
            }
            for (int i = 0; i < length; i++) {
            }
            bw.close();
            fw.close();
        } catch (IOException ex) {
            System.out.println("File Not Found");
          }

    }

    public int[][] readMatrix(int adjMatrix[][]) {

        try {
            File file = new File("matrix.txt");
            FileReader fr = new FileReader(file);
            BufferedReader br = new BufferedReader(fr);
            int i = 0;
            while (br.ready()) {
                String line = br.readLine();
                String array[] = line.split("@");
                for (int j = 0; j < adjMatrix.length; j++) {
                    adjMatrix[i][j] = Integer.parseInt(array[j]);
                }
                i++;
            }
        } catch (Exception e) {
            System.out.println("Error " + e);
        }
        return adjMatrix;
    }
}