Node:Stream Example, Previous:Exceptions from C, Up:Mixing Examples
This is a small example how to initialize a bidirectional socket
stream (error handling omitted):
typedef struct { int fd; /* socket number */ FILE *r_stream; /* For reading */ FILE *w_stream; /* For writing */ } SocketData; int socket_sgetc(SocketData *socket) { return fgetc(socket->r_stream); } int socket_sputc(char c, SocketData *socket) { return fputc(c, socket->w_stream); } int socket_sflush(SocketData *socket) { return fflush(socket->w_stream); } int socket_seof(SocketData *socket) { return feof(socket->r_stream); } void socket_sclrerr(SocketData *socket) { clearerr(socket->r_stream); clearerr(socket->w_stream); } int socket_sclose(SocketData *socket) { fclose(socket->r_stream); fclose(socket->w_stream); close(socket->fd); free(socket); return 0; } SP_stream *new_socket_stream(int fd) { SP_stream *stream; SocketData *socket; /* Allocate and initialize data local to socket */ socket = (SocketData *)malloc(sizeof(SocketData)); socket->fd = fd; socket->r_stream = fdopen(fd,"r"); socket->w_stream = fdopen(fd,"w"); /* Allocate and initialize Prolog stream */ SP_make_stream( socket, socket_sgetc, socket_sputc, socket_sflush, socket_seof, socket_sclrerr, socket_sclose, &stream); /* Allocate and copy string */ stream->filename = "socket"; stream->fd = fd; return stream; }