xref: /original-bsd/usr.bin/f77/libI77/endfile.c (revision 0b685140)
1 /*
2 char id_endfile[] = "@(#)endfile.c	1.5";
3  *
4  * endfile
5  */
6 
7 #include "fio.h"
8 
9 char endf[] = "endfile";
10 extern char *tmplate;
11 
12 f_end(a) alist *a;
13 {
14 	unit *b;
15 	lfname = NULL;
16 	elist = NO;
17 	errflag = a->aerr;
18 	lunit = a->aunit;
19 	if (not_legal(lunit)) err(errflag,F_ERUNIT,endf)
20 	b = &units[lunit];
21 	if(!b->ufd) err(errflag,F_ERNOPEN,endf)
22 	if(b->uend) return(0);
23 	lfname = b->ufnm;
24 	b->uend = YES;
25 	return(t_runc(b,errflag));
26 }
27 
28 t_runc(b,flag) unit *b; ioflag flag;
29 {
30 	char buf[128],nm[16];
31 	FILE *tmp;
32 	int n,m;
33 	long loc,len;
34 	fflush(b->ufd);
35 	if(b->url || !b->useek || !b->ufnm) return(OK); /*don't trunc dir files*/
36 	if(b->uwrt && ! nowreading(b)) err(errflag, errno, endf);
37 	loc=ftell(b->ufd);
38 	fseek(b->ufd,0L,2);
39 	len=ftell(b->ufd);
40 	if (loc>=len) return(OK);
41 	strcpy(nm,tmplate);
42 	mktemp(nm);
43 	if(!(tmp=fopen(nm,"w"))) err(flag,errno,endf);
44 	fseek(b->ufd,0L,0);
45 	while (loc)
46 	{
47 		n=fread(buf,1,loc>sizeof(buf)?sizeof(buf):(int)loc,b->ufd);
48 		loc -= n;
49 		fwrite(buf,1,n,tmp);
50 	}
51 	fflush(tmp);
52 	for(n=0;n<10;n++)
53 	{
54 		if((m=fork())==-1) continue;
55 		else if(m==0)
56 		{
57 			execl("/bin/cp","cp",nm,b->ufnm,0);
58 			execl("/usr/bin/cp","cp",nm,b->ufnm,0);
59 			fatal(F_ERSYS,"no cp for trunc");
60 		}
61 		wait(&m);
62 		if(m) err(flag,F_ERTRUNC,endf);
63 		fclose(tmp);
64 		unlink(nm);
65 		return(OK);
66 	}
67 	err(flag,F_ERTRUNC,endf);
68 }
69