Question
In C, implement a stack to store and remove integers that will be read from a file. The data
file contains a series of integers, one per line. There are two kinds of data in the file. Any
integer > -99999 is an int that will be pushed onto your stack. Whenever you read
-99999, this is a signal to pop your stack.
The format of the data file is:
<int to push>
<int to push>
Explanation / Answer
#include #include #include #include #include #include #include #include #include // For server #include // For client #define PORT 5000 #define BUF_SIZE 256 int client(const char* filename) { /* Create file where data will be stored */ FILE *fp = fopen(filename, "ab"); if(NULL == fp) { printf("Error opening file"); return 1; } /* Create a socket first */ int sockfd = 0; if((sockfd = socket(AF_INET, SOCK_STREAM, 0))< 0) { printf(" Error : Could not create socket "); return 1; } /* Initialize sockaddr_in data structure */ struct sockaddr_in serv_addr; serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(PORT); // port serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); /* Attempt a connection */ if(connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) 0) { printf("Bytes received %d ",bytesReceived); fwrite(buff, 1,bytesReceived,fp); } if(bytesReceived < 0) { printf(" Read Error "); } return 0; } int server(const char * filename) { int listenfd = socket(AF_INET, SOCK_STREAM, 0); printf("Socket retrieve success "); struct sockaddr_in serv_addr; memset(&serv_addr, '0', sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(PORT); bind(listenfd, (struct sockaddr*)&serv_addr,sizeof(serv_addr)); if(listen(listenfd, 10) == -1) { printf("Failed to listen "); return -1; } for (;;) { int connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL); /* Open the file that we wish to transfer */ FILE *fp = fopen(filename,"rb"); if(fp==NULL) { printf("File opern error"); return 1; } /* Read data from file and send it */ for (;;) { /* First read file in chunks of BUF_SIZE bytes */ unsigned char buff[BUF_SIZE]={0}; int nread = fread(buff,1,BUF_SIZE,fp); printf("Bytes read %d ", nread); /* If read was success, send data. */ if(nread > 0) { printf("Sending "); write(connfd, buff, nread); } /* * There is something tricky going on with read .. * Either there was error, or we reached end of file. */ if (nread