xref: /csrg-svn/usr.bin/f77/libI77/util.c (revision 12007)
1 /*
2 char id_util[] = "@(#)util.c	1.6";
3  *
4  * utility routines
5  */
6 
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include "fio.h"
10 
11 extern short	ccntrl_, blzero_;
12 
13 ini_std(u,F,w) FILE *F;
14 {	unit *p;
15 	p = &units[u];
16 	p->ufd = F;
17 	p->ufnm = NULL;
18 	p->useek = canseek(F);
19 	p->ufmt = YES;
20 	p->uwrt = (w==WRITE)? YES : NO;
21 	p->uscrtch = p->uend = NO;
22 	p->ublnk = blzero_;
23 	p->uprnt = ccntrl_;
24 	p->url = 0;
25 	p->uinode = finode(F);
26 }
27 
28 canseek(f) FILE *f; /*SYSDEP*/
29 {	struct stat x;
30 	return( (fstat(fileno(f),&x)==0) &&
31 	(x.st_nlink > 0 /*!pipe*/) && !isatty(fileno(f)) );
32 }
33 
34 nowreading(x) unit *x;
35 {
36 	return(now_acc(x,"r"));
37 }
38 
39 nowwriting(x) unit *x;
40 {
41 	return(now_acc(x,"a"));
42 }
43 
44 now_acc(x,mode)
45 unit *x; char *mode;
46 {
47 	long loc;
48 
49 	if (!x->ufnm)
50 	{
51 		errno = EBADF;
52 		return(NO);
53 	}
54 	if (x->useek)
55 		loc=ftell(x->ufd);
56 	if (freopen(x->ufnm,mode,x->ufd))
57 	{
58 		if (x->useek)
59 			fseek(x->ufd,loc,0);
60 		x->uwrt = (*mode=='a');
61 		return(YES);
62 	}
63 	if (x->ufd = fopen(x->ufnm, (*mode=='a')? "r":"a"))
64 		if (x->useek)
65 			fseek(x->ufd,loc,0);
66 	return(NO);
67 }
68 
69 g_char(a,alen,b) char *a,*b; ftnlen alen;
70 {	char *x=a+alen-1, *y=b+alen-1;
71 	while (x >= a  &&  *x == ' ') {x--; y--;}
72 	*(y+1) = '\0';
73 	while (x >= a) *y-- = *x--;
74 }
75 
76 b_char(from, to, tolen) char *from, *to; ftnlen tolen;
77 {	int i=0;
78 	while (*from && i < tolen) {
79 		*to++ = *from++;
80 		i++;
81 	}
82 	while (i++ < tolen)
83 		*to++ = ' ';
84 }
85 
86 inode(a) char *a;
87 {	struct stat x;
88 	if(stat(a,&x)==0) return(x.st_ino);
89 	else return(-1);
90 }
91 
92 finode(f) FILE *f;
93 {	struct stat x;
94 	if(fstat(fileno(f),&x)==0) return(x.st_ino);
95 	else return(-1);
96 }
97 
98 char
99 last_char(f) FILE *f;
100 {
101 	fseek(f,-2L,1);
102 	if(ftell(f)) return(getc(f));
103 	else return('\n');
104 }
105