* fports.c: #include <config.h> if HAVE_CONFIG_H.
[bpt/guile.git] / libguile / fports.c
1 /* Copyright (C) 1995,1996,1997,1998,1999,2000,2001, 2002 Free Software Foundation, Inc.
2 *
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2, or (at your option)
6 * any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this software; see the file COPYING. If not, write to
15 * the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
16 * Boston, MA 02111-1307 USA
17 *
18 * As a special exception, the Free Software Foundation gives permission
19 * for additional uses of the text contained in its release of GUILE.
20 *
21 * The exception is that, if you link the GUILE library with other files
22 * to produce an executable, this does not by itself cause the
23 * resulting executable to be covered by the GNU General Public License.
24 * Your use of that executable is in no way restricted on account of
25 * linking the GUILE library code into it.
26 *
27 * This exception does not however invalidate any other reasons why
28 * the executable file might be covered by the GNU General Public License.
29 *
30 * This exception applies only to the code released by the
31 * Free Software Foundation under the name GUILE. If you copy
32 * code from other Free Software Foundation releases into a copy of
33 * GUILE, as the General Public License permits, the exception does
34 * not apply to the code that you add in this way. To avoid misleading
35 * anyone as to the status of such modified files, you must delete
36 * this exception notice from them.
37 *
38 * If you write modifications of your own for GUILE, it is your choice
39 * whether to permit this exception to apply to your modifications.
40 * If you do not wish that, delete this exception notice. */
41
42
43 \f
44 #if HAVE_CONFIG_H
45 # include <config.h>
46 #endif
47
48 #include <stdio.h>
49 #include <fcntl.h>
50 #include "libguile/_scm.h"
51 #include "libguile/strings.h"
52 #include "libguile/validate.h"
53 #include "libguile/gc.h"
54
55 #include "libguile/fports.h"
56
57 #ifdef HAVE_STRING_H
58 #include <string.h>
59 #endif
60 #ifdef HAVE_UNISTD_H
61 #include <unistd.h>
62 #else
63 size_t fwrite ();
64 #endif
65 #ifdef HAVE_IO_H
66 #include <io.h>
67 #endif
68 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
69 #include <sys/stat.h>
70 #endif
71
72 #include <errno.h>
73
74 #include "libguile/iselect.h"
75
76 /* Some defines for Windows (native port, not Cygwin). */
77 #ifdef __MINGW32__
78 # include <sys/stat.h>
79 # include <winsock2.h>
80 # define ftruncate(fd, size) chsize (fd, size)
81 #endif /* __MINGW32__ */
82
83
84 scm_t_bits scm_tc16_fport;
85
86
87 /* default buffer size, used if the O/S won't supply a value. */
88 static const size_t default_buffer_size = 1024;
89
90 /* create FPORT buffer with specified sizes (or -1 to use default size or
91 0 for no buffer. */
92 static void
93 scm_fport_buffer_add (SCM port, long read_size, int write_size)
94 #define FUNC_NAME "scm_fport_buffer_add"
95 {
96 scm_t_port *pt = SCM_PTAB_ENTRY (port);
97
98 if (read_size == -1 || write_size == -1)
99 {
100 size_t default_size;
101 #ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
102 struct stat st;
103 scm_t_fport *fp = SCM_FSTREAM (port);
104
105 default_size = (fstat (fp->fdes, &st) == -1) ? default_buffer_size
106 : st.st_blksize;
107 #else
108 default_size = default_buffer_size;
109 #endif
110 if (read_size == -1)
111 read_size = default_size;
112 if (write_size == -1)
113 write_size = default_size;
114 }
115
116 if (SCM_INPUT_PORT_P (port) && read_size > 0)
117 {
118 pt->read_buf = scm_gc_malloc (read_size, "port buffer");
119 pt->read_pos = pt->read_end = pt->read_buf;
120 pt->read_buf_size = read_size;
121 }
122 else
123 {
124 pt->read_pos = pt->read_buf = pt->read_end = &pt->shortbuf;
125 pt->read_buf_size = 1;
126 }
127
128 if (SCM_OUTPUT_PORT_P (port) && write_size > 0)
129 {
130 pt->write_buf = scm_gc_malloc (write_size, "port buffer");
131 pt->write_pos = pt->write_buf;
132 pt->write_buf_size = write_size;
133 }
134 else
135 {
136 pt->write_buf = pt->write_pos = &pt->shortbuf;
137 pt->write_buf_size = 1;
138 }
139
140 pt->write_end = pt->write_buf + pt->write_buf_size;
141 if (read_size > 0 || write_size > 0)
142 SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) & ~SCM_BUF0);
143 else
144 SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) | SCM_BUF0);
145 }
146 #undef FUNC_NAME
147
148 SCM_DEFINE (scm_setvbuf, "setvbuf", 2, 1, 0,
149 (SCM port, SCM mode, SCM size),
150 "Set the buffering mode for @var{port}. @var{mode} can be:\n"
151 "@table @code\n"
152 "@item _IONBF\n"
153 "non-buffered\n"
154 "@item _IOLBF\n"
155 "line buffered\n"
156 "@item _IOFBF\n"
157 "block buffered, using a newly allocated buffer of @var{size} bytes.\n"
158 "If @var{size} is omitted, a default size will be used.\n"
159 "@end table")
160 #define FUNC_NAME s_scm_setvbuf
161 {
162 int cmode;
163 long csize;
164 scm_t_port *pt;
165
166 port = SCM_COERCE_OUTPORT (port);
167
168 SCM_VALIDATE_OPFPORT (1,port);
169 SCM_VALIDATE_INUM_COPY (2,mode,cmode);
170 if (cmode != _IONBF && cmode != _IOFBF && cmode != _IOLBF)
171 scm_out_of_range (FUNC_NAME, mode);
172
173 if (cmode == _IOLBF)
174 {
175 SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) | SCM_BUFLINE);
176 cmode = _IOFBF;
177 }
178 else
179 {
180 SCM_SET_CELL_WORD_0 (port, SCM_CELL_WORD_0 (port) ^ SCM_BUFLINE);
181 }
182
183 if (SCM_UNBNDP (size))
184 {
185 if (cmode == _IOFBF)
186 csize = -1;
187 else
188 csize = 0;
189 }
190 else
191 {
192 SCM_VALIDATE_INUM_COPY (3,size,csize);
193 if (csize < 0 || (cmode == _IONBF && csize > 0))
194 scm_out_of_range (FUNC_NAME, size);
195 }
196
197 pt = SCM_PTAB_ENTRY (port);
198
199 /* silently discards buffered and put-back chars. */
200 if (pt->read_buf == pt->putback_buf)
201 {
202 pt->read_buf = pt->saved_read_buf;
203 pt->read_pos = pt->saved_read_pos;
204 pt->read_end = pt->saved_read_end;
205 pt->read_buf_size = pt->saved_read_buf_size;
206 }
207 if (pt->read_buf != &pt->shortbuf)
208 scm_gc_free (pt->read_buf, pt->read_buf_size, "port buffer");
209 if (pt->write_buf != &pt->shortbuf)
210 scm_gc_free (pt->write_buf, pt->write_buf_size, "port buffer");
211
212 scm_fport_buffer_add (port, csize, csize);
213 return SCM_UNSPECIFIED;
214 }
215 #undef FUNC_NAME
216
217 /* Move ports with the specified file descriptor to new descriptors,
218 * resetting the revealed count to 0.
219 */
220
221 void
222 scm_evict_ports (int fd)
223 {
224 long i;
225
226 for (i = 0; i < scm_i_port_table_size; i++)
227 {
228 SCM port = scm_i_port_table[i]->port;
229
230 if (SCM_FPORTP (port))
231 {
232 scm_t_fport *fp = SCM_FSTREAM (port);
233
234 if (fp->fdes == fd)
235 {
236 fp->fdes = dup (fd);
237 if (fp->fdes == -1)
238 scm_syserror ("scm_evict_ports");
239 scm_set_port_revealed_x (port, SCM_MAKINUM (0));
240 }
241 }
242 }
243 }
244
245
246 SCM_DEFINE (scm_file_port_p, "file-port?", 1, 0, 0,
247 (SCM obj),
248 "Determine whether @var{obj} is a port that is related to a file.")
249 #define FUNC_NAME s_scm_file_port_p
250 {
251 return SCM_BOOL (SCM_FPORTP (obj));
252 }
253 #undef FUNC_NAME
254
255
256 /* scm_open_file
257 * Return a new port open on a given file.
258 *
259 * The mode string must match the pattern: [rwa+]** which
260 * is interpreted in the usual unix way.
261 *
262 * Return the new port.
263 */
264 SCM_DEFINE (scm_open_file, "open-file", 2, 0, 0,
265 (SCM filename, SCM mode),
266 "Open the file whose name is @var{filename}, and return a port\n"
267 "representing that file. The attributes of the port are\n"
268 "determined by the @var{mode} string. The way in which this is\n"
269 "interpreted is similar to C stdio. The first character must be\n"
270 "one of the following:\n"
271 "@table @samp\n"
272 "@item r\n"
273 "Open an existing file for input.\n"
274 "@item w\n"
275 "Open a file for output, creating it if it doesn't already exist\n"
276 "or removing its contents if it does.\n"
277 "@item a\n"
278 "Open a file for output, creating it if it doesn't already\n"
279 "exist. All writes to the port will go to the end of the file.\n"
280 "The \"append mode\" can be turned off while the port is in use\n"
281 "@pxref{Ports and File Descriptors, fcntl}\n"
282 "@end table\n"
283 "The following additional characters can be appended:\n"
284 "@table @samp\n"
285 "@item +\n"
286 "Open the port for both input and output. E.g., @code{r+}: open\n"
287 "an existing file for both input and output.\n"
288 "@item 0\n"
289 "Create an \"unbuffered\" port. In this case input and output\n"
290 "operations are passed directly to the underlying port\n"
291 "implementation without additional buffering. This is likely to\n"
292 "slow down I/O operations. The buffering mode can be changed\n"
293 "while a port is in use @pxref{Ports and File Descriptors,\n"
294 "setvbuf}\n"
295 "@item l\n"
296 "Add line-buffering to the port. The port output buffer will be\n"
297 "automatically flushed whenever a newline character is written.\n"
298 "@end table\n"
299 "In theory we could create read/write ports which were buffered\n"
300 "in one direction only. However this isn't included in the\n"
301 "current interfaces. If a file cannot be opened with the access\n"
302 "requested, @code{open-file} throws an exception.")
303 #define FUNC_NAME s_scm_open_file
304 {
305 SCM port;
306 int fdes;
307 int flags = 0;
308 char *file;
309 char *md;
310 char *ptr;
311
312 SCM_VALIDATE_STRING (1, filename);
313 SCM_VALIDATE_STRING (2, mode);
314
315 file = SCM_STRING_CHARS (filename);
316 md = SCM_STRING_CHARS (mode);
317
318 switch (*md)
319 {
320 case 'r':
321 flags |= O_RDONLY;
322 break;
323 case 'w':
324 flags |= O_WRONLY | O_CREAT | O_TRUNC;
325 break;
326 case 'a':
327 flags |= O_WRONLY | O_CREAT | O_APPEND;
328 break;
329 default:
330 scm_out_of_range (FUNC_NAME, mode);
331 }
332 ptr = md + 1;
333 while (*ptr != '\0')
334 {
335 switch (*ptr)
336 {
337 case '+':
338 flags = (flags & ~(O_RDONLY | O_WRONLY)) | O_RDWR;
339 break;
340 case 'b':
341 #if defined (O_BINARY)
342 flags |= O_BINARY;
343 #endif
344 break;
345 case '0': /* unbuffered: handled later. */
346 case 'l': /* line buffered: handled during output. */
347 break;
348 default:
349 scm_out_of_range (FUNC_NAME, mode);
350 }
351 ptr++;
352 }
353 SCM_SYSCALL (fdes = open (file, flags, 0666));
354 if (fdes == -1)
355 {
356 int en = errno;
357
358 SCM_SYSERROR_MSG ("~A: ~S",
359 scm_cons (scm_makfrom0str (strerror (en)),
360 scm_cons (filename, SCM_EOL)), en);
361 }
362 port = scm_fdes_to_port (fdes, md, filename);
363 return port;
364 }
365 #undef FUNC_NAME
366
367 \f
368 #ifdef __MINGW32__
369 /*
370 * Try getting the appropiate file flags for a given file descriptor
371 * under Windows. This incorporates some fancy operations because Windows
372 * differentiates between file, pipe and socket descriptors.
373 */
374 #ifndef O_ACCMODE
375 # define O_ACCMODE 0x0003
376 #endif
377
378 static int getflags (int fdes)
379 {
380 int flags = 0;
381 struct stat buf;
382 int error, optlen = sizeof (int);
383
384 /* Is this a socket ? */
385 if (getsockopt (fdes, SOL_SOCKET, SO_ERROR, (void *) &error, &optlen) >= 0)
386 flags = O_RDWR;
387 /* Maybe a regular file ? */
388 else if (fstat (fdes, &buf) < 0)
389 flags = -1;
390 else
391 {
392 /* Or an anonymous pipe handle ? */
393 if (buf.st_mode & _S_IFIFO)
394 flags = PeekNamedPipe ((HANDLE) _get_osfhandle (fdes), NULL, 0,
395 NULL, NULL, NULL) ? O_RDONLY : O_WRONLY;
396 /* stdin ? */
397 else if (fdes == fileno (stdin) && isatty (fdes))
398 flags = O_RDONLY;
399 /* stdout / stderr ? */
400 else if ((fdes == fileno (stdout) || fdes == fileno (stderr)) &&
401 isatty (fdes))
402 flags = O_WRONLY;
403 else
404 flags = buf.st_mode;
405 }
406 return flags;
407 }
408 #endif /* __MINGW32__ */
409
410 /* Building Guile ports from a file descriptor. */
411
412 /* Build a Scheme port from an open file descriptor `fdes'.
413 MODE indicates whether FILE is open for reading or writing; it uses
414 the same notation as open-file's second argument.
415 NAME is a string to be used as the port's filename.
416 */
417 SCM
418 scm_fdes_to_port (int fdes, char *mode, SCM name)
419 #define FUNC_NAME "scm_fdes_to_port"
420 {
421 long mode_bits = scm_mode_bits (mode);
422 SCM port;
423 scm_t_port *pt;
424 int flags;
425
426 /* test that fdes is valid. */
427 #ifdef __MINGW32__
428 flags = getflags (fdes);
429 #else
430 flags = fcntl (fdes, F_GETFL, 0);
431 #endif
432 if (flags == -1)
433 SCM_SYSERROR;
434 flags &= O_ACCMODE;
435 if (flags != O_RDWR
436 && ((flags != O_WRONLY && (mode_bits & SCM_WRTNG))
437 || (flags != O_RDONLY && (mode_bits & SCM_RDNG))))
438 {
439 SCM_MISC_ERROR ("requested file mode not available on fdes", SCM_EOL);
440 }
441
442 SCM_DEFER_INTS;
443
444 port = scm_new_port_table_entry (scm_tc16_fport);
445 SCM_SET_CELL_TYPE(port, scm_tc16_fport | mode_bits);
446 pt = SCM_PTAB_ENTRY(port);
447 {
448 scm_t_fport *fp
449 = (scm_t_fport *) scm_gc_malloc (sizeof (scm_t_fport), "file port");
450
451 fp->fdes = fdes;
452 pt->rw_random = SCM_FDES_RANDOM_P (fdes);
453 SCM_SETSTREAM (port, fp);
454 if (mode_bits & SCM_BUF0)
455 scm_fport_buffer_add (port, 0, 0);
456 else
457 scm_fport_buffer_add (port, -1, -1);
458 }
459 SCM_SET_FILENAME (port, name);
460 SCM_ALLOW_INTS;
461 return port;
462 }
463 #undef FUNC_NAME
464
465 /* Return a lower bound on the number of bytes available for input. */
466 static int
467 fport_input_waiting (SCM port)
468 {
469 int fdes = SCM_FSTREAM (port)->fdes;
470
471 #ifdef HAVE_SELECT
472 struct timeval timeout;
473 SELECT_TYPE read_set;
474 SELECT_TYPE write_set;
475 SELECT_TYPE except_set;
476
477 FD_ZERO (&read_set);
478 FD_ZERO (&write_set);
479 FD_ZERO (&except_set);
480
481 FD_SET (fdes, &read_set);
482
483 timeout.tv_sec = 0;
484 timeout.tv_usec = 0;
485
486 if (select (SELECT_SET_SIZE,
487 &read_set, &write_set, &except_set, &timeout)
488 < 0)
489 scm_syserror ("fport_input_waiting");
490 return FD_ISSET (fdes, &read_set) ? 1 : 0;
491 #elif defined (FIONREAD)
492 int remir;
493 ioctl(fdes, FIONREAD, &remir);
494 return remir;
495 #else
496 scm_misc_error ("fport_input_waiting",
497 "Not fully implemented on this platform",
498 SCM_EOL);
499 #endif
500 }
501
502 \f
503 static int
504 fport_print (SCM exp, SCM port, scm_print_state *pstate SCM_UNUSED)
505 {
506 scm_puts ("#<", port);
507 scm_print_port_mode (exp, port);
508 if (SCM_OPFPORTP (exp))
509 {
510 int fdes;
511 SCM name = SCM_FILENAME (exp);
512 if (SCM_STRINGP (name) || SCM_SYMBOLP (name))
513 scm_display (name, port);
514 else
515 scm_puts (SCM_PTOBNAME (SCM_PTOBNUM (exp)), port);
516 scm_putc (' ', port);
517 fdes = (SCM_FSTREAM (exp))->fdes;
518
519 #ifdef HAVE_TTYNAME
520 if (isatty (fdes))
521 scm_puts (ttyname (fdes), port);
522 else
523 #endif /* HAVE_TTYNAME */
524 scm_intprint (fdes, 10, port);
525 }
526 else
527 {
528 scm_puts (SCM_PTOBNAME (SCM_PTOBNUM (exp)), port);
529 scm_putc (' ', port);
530 scm_intprint ((scm_t_bits) SCM_PTAB_ENTRY (exp), 16, port);
531 }
532 scm_putc ('>', port);
533 return 1;
534 }
535
536 /* thread-local block for input on fport's fdes. */
537 static void
538 fport_wait_for_input (SCM port)
539 {
540 int fdes = SCM_FSTREAM (port)->fdes;
541
542 if (!fport_input_waiting (port))
543 {
544 int n;
545 SELECT_TYPE readfds;
546 int flags = fcntl (fdes, F_GETFL);
547
548 if (flags == -1)
549 scm_syserror ("scm_fdes_wait_for_input");
550 if (!(flags & O_NONBLOCK))
551 do
552 {
553 FD_ZERO (&readfds);
554 FD_SET (fdes, &readfds);
555 n = scm_internal_select (fdes + 1, &readfds, NULL, NULL, NULL);
556 }
557 while (n == -1 && errno == EINTR);
558 }
559 }
560
561 static void fport_flush (SCM port);
562
563 /* fill a port's read-buffer with a single read. returns the first
564 char or EOF if end of file. */
565 static int
566 fport_fill_input (SCM port)
567 {
568 long count;
569 scm_t_port *pt = SCM_PTAB_ENTRY (port);
570 scm_t_fport *fp = SCM_FSTREAM (port);
571
572 fport_wait_for_input (port);
573 SCM_SYSCALL (count = read (fp->fdes, pt->read_buf, pt->read_buf_size));
574 if (count == -1)
575 scm_syserror ("fport_fill_input");
576 if (count == 0)
577 return EOF;
578 else
579 {
580 pt->read_pos = pt->read_buf;
581 pt->read_end = pt->read_buf + count;
582 return *pt->read_buf;
583 }
584 }
585
586 static off_t
587 fport_seek (SCM port, off_t offset, int whence)
588 {
589 scm_t_port *pt = SCM_PTAB_ENTRY (port);
590 scm_t_fport *fp = SCM_FSTREAM (port);
591 off_t rv;
592 off_t result;
593
594 if (pt->rw_active == SCM_PORT_WRITE)
595 {
596 if (offset != 0 || whence != SEEK_CUR)
597 {
598 fport_flush (port);
599 result = rv = lseek (fp->fdes, offset, whence);
600 }
601 else
602 {
603 /* read current position without disturbing the buffer. */
604 rv = lseek (fp->fdes, offset, whence);
605 result = rv + (pt->write_pos - pt->write_buf);
606 }
607 }
608 else if (pt->rw_active == SCM_PORT_READ)
609 {
610 if (offset != 0 || whence != SEEK_CUR)
611 {
612 /* could expand to avoid a second seek. */
613 scm_end_input (port);
614 result = rv = lseek (fp->fdes, offset, whence);
615 }
616 else
617 {
618 /* read current position without disturbing the buffer
619 (particularly the unread-char buffer). */
620 rv = lseek (fp->fdes, offset, whence);
621 result = rv - (pt->read_end - pt->read_pos);
622
623 if (pt->read_buf == pt->putback_buf)
624 result -= pt->saved_read_end - pt->saved_read_pos;
625 }
626 }
627 else /* SCM_PORT_NEITHER */
628 {
629 result = rv = lseek (fp->fdes, offset, whence);
630 }
631
632 if (rv == -1)
633 scm_syserror ("fport_seek");
634
635 return result;
636 }
637
638 static void
639 fport_truncate (SCM port, off_t length)
640 {
641 scm_t_fport *fp = SCM_FSTREAM (port);
642
643 if (ftruncate (fp->fdes, length) == -1)
644 scm_syserror ("ftruncate");
645 }
646
647 /* helper for fport_write: try to write data, using multiple system
648 calls if required. */
649 #define FUNC_NAME "write_all"
650 static void write_all (SCM port, const void *data, size_t remaining)
651 {
652 int fdes = SCM_FSTREAM (port)->fdes;
653
654 while (remaining > 0)
655 {
656 size_t done;
657
658 SCM_SYSCALL (done = write (fdes, data, remaining));
659
660 if (done == -1)
661 SCM_SYSERROR;
662 remaining -= done;
663 data = ((const char *) data) + done;
664 }
665 }
666 #undef FUNC_NAME
667
668 static void
669 fport_write (SCM port, const void *data, size_t size)
670 {
671 /* this procedure tries to minimize the number of writes/flushes. */
672 scm_t_port *pt = SCM_PTAB_ENTRY (port);
673
674 if (pt->write_buf == &pt->shortbuf
675 || (pt->write_pos == pt->write_buf && size >= pt->write_buf_size))
676 {
677 /* "unbuffered" port, or
678 port with empty buffer and data won't fit in buffer. */
679 write_all (port, data, size);
680 return;
681 }
682
683 {
684 off_t space = pt->write_end - pt->write_pos;
685
686 if (size <= space)
687 {
688 /* data fits in buffer. */
689 memcpy (pt->write_pos, data, size);
690 pt->write_pos += size;
691 if (pt->write_pos == pt->write_end)
692 {
693 fport_flush (port);
694 /* we can skip the line-buffering check if nothing's buffered. */
695 return;
696 }
697 }
698 else
699 {
700 memcpy (pt->write_pos, data, space);
701 pt->write_pos = pt->write_end;
702 fport_flush (port);
703 {
704 const void *ptr = ((const char *) data) + space;
705 size_t remaining = size - space;
706
707 if (size >= pt->write_buf_size)
708 {
709 write_all (port, ptr, remaining);
710 return;
711 }
712 else
713 {
714 memcpy (pt->write_pos, ptr, remaining);
715 pt->write_pos += remaining;
716 }
717 }
718 }
719
720 /* handle line buffering. */
721 if ((SCM_CELL_WORD_0 (port) & SCM_BUFLINE) && memchr (data, '\n', size))
722 fport_flush (port);
723 }
724 }
725
726 /* becomes 1 when process is exiting: normal exception handling won't
727 work by this time. */
728 extern int scm_i_terminating;
729
730 static void
731 fport_flush (SCM port)
732 {
733 scm_t_port *pt = SCM_PTAB_ENTRY (port);
734 scm_t_fport *fp = SCM_FSTREAM (port);
735 unsigned char *ptr = pt->write_buf;
736 long init_size = pt->write_pos - pt->write_buf;
737 long remaining = init_size;
738
739 while (remaining > 0)
740 {
741 long count;
742
743 SCM_SYSCALL (count = write (fp->fdes, ptr, remaining));
744 if (count < 0)
745 {
746 /* error. assume nothing was written this call, but
747 fix up the buffer for any previous successful writes. */
748 long done = init_size - remaining;
749
750 if (done > 0)
751 {
752 int i;
753
754 for (i = 0; i < remaining; i++)
755 {
756 *(pt->write_buf + i) = *(pt->write_buf + done + i);
757 }
758 pt->write_pos = pt->write_buf + remaining;
759 }
760 if (scm_i_terminating)
761 {
762 const char *msg = "Error: could not flush file-descriptor ";
763 char buf[11];
764
765 write (2, msg, strlen (msg));
766 sprintf (buf, "%d\n", fp->fdes);
767 write (2, buf, strlen (buf));
768
769 count = remaining;
770 }
771 else if (scm_gc_running_p)
772 {
773 /* silently ignore the error. scm_error would abort if we
774 called it now. */
775 count = remaining;
776 }
777 else
778 scm_syserror ("fport_flush");
779 }
780 ptr += count;
781 remaining -= count;
782 }
783 pt->write_pos = pt->write_buf;
784 pt->rw_active = SCM_PORT_NEITHER;
785 }
786
787 /* clear the read buffer and adjust the file position for unread bytes. */
788 static void
789 fport_end_input (SCM port, int offset)
790 {
791 scm_t_fport *fp = SCM_FSTREAM (port);
792 scm_t_port *pt = SCM_PTAB_ENTRY (port);
793
794 offset += pt->read_end - pt->read_pos;
795
796 if (offset > 0)
797 {
798 pt->read_pos = pt->read_end;
799 /* will throw error if unread-char used at beginning of file
800 then attempting to write. seems correct. */
801 if (lseek (fp->fdes, -offset, SEEK_CUR) == -1)
802 scm_syserror ("fport_end_input");
803 }
804 pt->rw_active = SCM_PORT_NEITHER;
805 }
806
807 static int
808 fport_close (SCM port)
809 {
810 scm_t_fport *fp = SCM_FSTREAM (port);
811 scm_t_port *pt = SCM_PTAB_ENTRY (port);
812 int rv;
813
814 fport_flush (port);
815 SCM_SYSCALL (rv = close (fp->fdes));
816 if (rv == -1 && errno != EBADF)
817 {
818 if (scm_gc_running_p)
819 /* silently ignore the error. scm_error would abort if we
820 called it now. */
821 ;
822 else
823 scm_syserror ("fport_close");
824 }
825 if (pt->read_buf == pt->putback_buf)
826 pt->read_buf = pt->saved_read_buf;
827 if (pt->read_buf != &pt->shortbuf)
828 scm_gc_free (pt->read_buf, pt->read_buf_size, "port buffer");
829 if (pt->write_buf != &pt->shortbuf)
830 scm_gc_free (pt->write_buf, pt->write_buf_size, "port buffer");
831 scm_gc_free (fp, sizeof (*fp), "file port");
832 return rv;
833 }
834
835 static size_t
836 fport_free (SCM port)
837 {
838 fport_close (port);
839 return 0;
840 }
841
842 static scm_t_bits
843 scm_make_fptob ()
844 {
845 scm_t_bits tc = scm_make_port_type ("file", fport_fill_input, fport_write);
846
847 scm_set_port_free (tc, fport_free);
848 scm_set_port_print (tc, fport_print);
849 scm_set_port_flush (tc, fport_flush);
850 scm_set_port_end_input (tc, fport_end_input);
851 scm_set_port_close (tc, fport_close);
852 scm_set_port_seek (tc, fport_seek);
853 scm_set_port_truncate (tc, fport_truncate);
854 scm_set_port_input_waiting (tc, fport_input_waiting);
855
856 return tc;
857 }
858
859 void
860 scm_init_fports ()
861 {
862 scm_tc16_fport = scm_make_fptob ();
863
864 scm_c_define ("_IOFBF", SCM_MAKINUM (_IOFBF));
865 scm_c_define ("_IOLBF", SCM_MAKINUM (_IOLBF));
866 scm_c_define ("_IONBF", SCM_MAKINUM (_IONBF));
867
868 #include "libguile/fports.x"
869 }
870
871 /*
872 Local Variables:
873 c-file-style: "gnu"
874 End:
875 */