1 static const char CVSID
[] = "$Id: fileUtils.c,v 1.32 2004/07/21 11:32:07 yooden Exp $";
2 /*******************************************************************************
4 * fileUtils.c -- File utilities for Nirvana applications *
6 * Copyright (C) 1999 Mark Edel *
8 * This is free software; you can redistribute it and/or modify it under the *
9 * terms of the GNU General Public License as published by the Free Software *
10 * Foundation; either version 2 of the License, or (at your option) any later *
11 * version. In addition, you may distribute version of this program linked to *
12 * Motif or Open Motif. See README for details. *
14 * This software is distributed in the hope that it will be useful, but WITHOUT *
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
16 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License *
19 * You should have received a copy of the GNU General Public License along with *
20 * software; if not, write to the Free Software Foundation, Inc., 59 Temple *
21 * Place, Suite 330, Boston, MA 02111-1307 USA *
23 * Nirvana Text Editor *
26 * Written by Mark Edel *
28 * Modified by: DMR - Ported to VMS (1st stage for Histo-Scope) *
30 *******************************************************************************/
33 #include "../config.h"
36 #include "fileUtils.h"
43 #include <X11/Intrinsic.h>
45 #define NULL (void *) 0
51 #include <sys/types.h>
53 #include <sys/param.h>
64 #ifndef MAXSYMLINKS /* should be defined in <sys/param.h> */
65 #define MAXSYMLINKS 20
71 /* Parameters to algorithm used to auto-detect DOS format files. NEdit will
72 scan up to the lesser of FORMAT_SAMPLE_LINES lines and FORMAT_SAMPLE_CHARS
73 characters of the beginning of the file, checking that all newlines are
74 paired with carriage returns. If even a single counterexample exists,
75 the file is judged to be in Unix format. */
76 #define FORMAT_SAMPLE_LINES 5
77 #define FORMAT_SAMPLE_CHARS 2000
79 static char *nextSlash(char *ptr
);
80 static char *prevSlash(char *ptr
);
81 static int compareThruSlash(const char *string1
, const char *string2
);
82 static void copyThruSlash(char **toString
, char **fromString
);
85 ** Decompose a Unix file name into a file name and a path.
86 ** Return non-zero value if it fails, zero else.
87 ** For now we assume that filename and pathname are at
88 ** least MAXPATHLEN chars long.
89 ** To skip setting filename or pathname pass NULL for that argument.
92 ParseFilename(const char *fullname
, char *filename
, char *pathname
)
94 int fullLen
= strlen(fullname
);
95 int i
, pathLen
, fileLen
;
98 /* find the last ] or : */
99 for (i
=fullLen
-1; i
>=0; i
--) {
100 if (fullname
[i
] == ']' || fullname
[i
] == ':')
104 char *viewExtendPath
;
107 /* For clearcase version extended paths, slash characters after the "@@/"
108 should be considered part of the file name, rather than the path */
109 if ((viewExtendPath
= strstr(fullname
, "@@/")) != NULL
)
110 scanStart
= viewExtendPath
- fullname
- 1;
112 scanStart
= fullLen
- 1;
114 /* find the last slash */
115 for (i
=scanStart
; i
>=0; i
--) {
116 if (fullname
[i
] == '/')
121 /* move chars before / (or ] or :) into pathname,& after into filename */
123 fileLen
= fullLen
- pathLen
;
125 if (pathLen
>= MAXPATHLEN
) {
128 strncpy(pathname
, fullname
, pathLen
);
129 pathname
[pathLen
] = 0;
132 if (fileLen
>= MAXPATHLEN
) {
135 strncpy(filename
, &fullname
[pathLen
], fileLen
);
136 filename
[fileLen
] = 0;
139 #ifndef VMS /* UNIX specific... Modify at a later date for VMS */
141 if (NormalizePathname(pathname
)) {
142 return 1; /* pathname too long */
144 pathLen
= strlen(pathname
);
148 if (filename
&& pathname
&& (pathLen
+ 1 + fileLen
) >= MAXPATHLEN
) {
149 return 1; /* pathname + filename too long */
158 ** Expand tilde characters which begin file names as done by the shell
159 ** If it doesn't work just out leave pathname unmodified.
160 ** This implementation is neither fast, nor elegant, nor ...
163 ExpandTilde(char *pathname
)
165 struct passwd
*passwdEntry
;
166 char username
[MAXPATHLEN
], temp
[MAXPATHLEN
];
170 if (pathname
[0] != '~')
172 nameEnd
= strchr(&pathname
[1], '/');
173 if (nameEnd
== NULL
) {
174 nameEnd
= pathname
+ strlen(pathname
);
176 strncpy(username
, &pathname
[1], nameEnd
- &pathname
[1]);
177 username
[nameEnd
- &pathname
[1]] = '\0';
178 /* We might consider to re-use the GetHomeDir() function,
179 but to keep the code more similar for both cases ... */
180 if (username
[0] == '\0') {
181 passwdEntry
= getpwuid(getuid());
182 if ((passwdEntry
== NULL
) || (*(passwdEntry
->pw_dir
)== '\0')) {
183 /* This is really serious, so just exit. */
184 perror("NEdit/nc: getpwuid() failed ");
189 passwdEntry
= getpwnam(username
);
190 if ((passwdEntry
== NULL
) || (*(passwdEntry
->pw_dir
)== '\0')) {
191 /* username was just an input by the user, this is no
192 indication for some (serious) problems */
197 strcpy(temp
, passwdEntry
->pw_dir
);
199 len_left
= sizeof(temp
)-strlen(temp
)-1;
200 if (len_left
< strlen(nameEnd
)) {
201 /* It won't work out */
204 strcat(temp
, nameEnd
);
205 strcpy(pathname
, temp
);
210 * Resolve symbolic links (if any) for the absolute path given in pathIn
211 * and place the resolved absolute path in pathResolved.
212 * - pathIn must contain an absolute path spec.
213 * - pathResolved must point to a buffer of minimum size MAXPATHLEN.
216 * TRUE if pathResolved contains a valid resolved path
217 * OR pathIn is not a symlink (pathResolved will have the same
218 * contents like pathIn)
220 * FALSE an error occured while trying to resolve the symlink, i.e.
221 * pathIn was no absolute path or the link is a loop.
224 ResolvePath(const char * pathIn
, char * pathResolved
)
226 char resolveBuf
[MAXPATHLEN
], pathBuf
[MAXPATHLEN
];
231 strncpy(pathResolved
, pathIn
, MAXPATHLEN
);
232 /* If there are no links at all, it's a valid "resolved" path */
235 /* !! readlink does NOT recognize loops, i.e. links like file -> ./file */
236 for(loops
=0; loops
<MAXSYMLINKS
; loops
++) {
238 rlResult
=readlink((char *)pathIn
, resolveBuf
, MAXPATHLEN
-1);
240 rlResult
=readlink(pathIn
, resolveBuf
, MAXPATHLEN
-1);
250 /* It's not a symlink - we are done */
251 strncpy(pathResolved
, pathIn
, MAXPATHLEN
);
252 pathResolved
[MAXPATHLEN
-1] = '\0';
258 } else if (rlResult
==0) {
262 resolveBuf
[rlResult
]=0;
264 if(resolveBuf
[0]!='/') {
265 strncpy(pathBuf
, pathIn
, MAXPATHLEN
);
266 pathBuf
[MAXPATHLEN
-1] = '\0';
267 pathEnd
=strrchr(pathBuf
, '/');
270 strcpy(pathEnd
+1, resolveBuf
);
272 strcpy(pathBuf
, resolveBuf
);
274 NormalizePathname(pathBuf
);
278 #endif /* NO_READLINK */
283 ** Return 0 if everything's fine. In fact it always return 0 ...
284 ** Capable to handle arbitrary path length (>MAXPATHLEN)!
287 NormalizePathname(char *pathname
)
289 /* if this is a relative pathname, prepend current directory */
291 /* OS/2, ...: welcome to the world of drive letters ... */
292 if (!_fnisabs(pathname
)) {
294 if (pathname
[0] != '/') {
299 /* make a copy of pathname to work from */
300 oldPathname
=(char *)malloc(strlen(pathname
)+1);
301 strcpy(oldPathname
, pathname
);
302 /* get the working directory and prepend to the path */
303 strcpy(pathname
, GetCurrentDir());
304 /* check for trailing slash, or pathname being root dir "/":
305 don't add a second '/' character as this may break things
306 on non-un*x systems */
307 len
=strlen(pathname
); /* GetCurrentDir() returns non-NULL value */
308 if ( len
==0 ? 1 : pathname
[len
-1] != '/' ) {
309 strcat(pathname
, "/");
311 strcat(pathname
, oldPathname
);
315 /* compress out .. and . */
316 return CompressPathname(pathname
);
321 ** Return 0 if everything's fine, 1 else.
324 CompressPathname(char *pathname
)
326 char *buf
, *inPtr
, *outPtr
;
329 /* (Added by schwarzenberg)
330 ** replace multiple slashes by a single slash
333 buf
=(char *)malloc(strlen(pathname
)+2);
344 strcpy(pathname
, buf
);
346 /* compress out . and .. */
350 copyThruSlash(&outPtr
, &inPtr
);
351 while (inPtr
!= NULL
) {
352 /* if the next component is "../", remove previous component */
353 if (compareThruSlash(inPtr
, "../")) {
355 /* If the ../ is at the beginning, or if the previous component
356 is a symbolic link, preserve the ../. It is not valid to
357 compress ../ when the previous component is a symbolic link
358 because ../ is relative to where the link points. If there's
359 no S_ISLNK macro, assume system does not do symbolic links. */
361 if(outPtr
-1 == buf
|| (lstat(buf
, &statbuf
) == 0 &&
362 S_ISLNK(statbuf
.st_mode
))) {
363 copyThruSlash(&outPtr
, &inPtr
);
367 /* back up outPtr to remove last path name component */
368 outPtr
= prevSlash(outPtr
);
369 inPtr
= nextSlash(inPtr
);
371 } else if (compareThruSlash(inPtr
, "./")) {
372 /* don't copy the component if it's the redundant "./" */
373 inPtr
= nextSlash(inPtr
);
375 /* copy the component to outPtr */
376 copyThruSlash(&outPtr
, &inPtr
);
379 /* updated pathname with the new value */
380 if (strlen(buf
)>MAXPATHLEN
) {
381 fprintf(stderr
, "NEdit: CompressPathname(): file name too long %s\n",
387 strcpy(pathname
, buf
);
394 *nextSlash(char *ptr
)
396 for(; *ptr
!='/'; ptr
++) {
404 *prevSlash(char *ptr
)
406 for(ptr
-= 2; *ptr
!='/'; ptr
--);
411 compareThruSlash(const char *string1
, const char *string2
)
414 if (*string1
!= *string2
)
416 if (*string1
=='\0' || *string1
=='/')
424 copyThruSlash(char **toString
, char **fromString
)
426 char *to
= *toString
;
427 char *from
= *fromString
;
437 *fromString
= from
+ 1;
448 ** Dummy versions of the public functions for VMS.
452 ** Return 0 if everything's fine, 1 else.
454 int NormalizePathname(char *pathname
)
460 ** Return 0 if everything's fine, 1 else.
462 int CompressPathname(char *pathname
)
469 * TRUE if no error occured
471 * FALSE if an error occured.
473 int ResolvePath(const char * pathIn
, char * pathResolved
)
475 if (strlen(pathIn
) < MAXPATHLEN
) {
476 strcpy(pathResolved
, pathIn
);
486 ** Return the trailing 'n' no. of path components
489 *GetTrailingPathComponents(const char* path
,
492 /* Start from the rear */
493 const char* ptr
= path
+ strlen(path
);
496 while (--ptr
> path
) {
498 if (count
++ == noOfComponents
) {
507 ** Samples up to a maximum of FORMAT_SAMPLE_LINES lines and FORMAT_SAMPLE_CHARS
508 ** characters, to determine whether fileString represents a MS DOS or Macintosh
509 ** format file. If there's ANY ambiguity (a newline in the sample not paired
510 ** with a return in an otherwise DOS looking file, or a newline appearing in
511 ** the sampled portion of a Macintosh looking file), the file is judged to be
514 int FormatOfFile(const char *fileString
)
517 int nNewlines
= 0, nReturns
= 0;
519 for (p
=fileString
; *p
!='\0' && p
< fileString
+ FORMAT_SAMPLE_CHARS
; p
++) {
522 if (p
== fileString
|| *(p
-1) != '\r')
523 return UNIX_FILE_FORMAT
;
524 if (nNewlines
>= FORMAT_SAMPLE_LINES
)
525 return DOS_FILE_FORMAT
;
526 } else if (*p
== '\r')
530 return DOS_FILE_FORMAT
;
532 return MAC_FILE_FORMAT
;
533 return UNIX_FILE_FORMAT
;
537 ** Converts a string (which may represent the entire contents of the file)
538 ** from DOS or Macintosh format to Unix format. Conversion is done in-place.
539 ** In the DOS case, the length will be shorter, and passed length will be
540 ** modified to reflect the new length. The routine has support for blockwise
541 ** file to string conversion: if the fileString has a trailing '\r' and
542 ** 'pendingCR' is not zero, the '\r' is deposited in there and is not
543 ** converted. If there is no trailing '\r', a 0 is deposited in 'pendingCR'
544 ** It's the caller's responsability to make sure that the pending character,
545 ** if present, is inserted at the beginning of the next block to convert.
547 void ConvertFromDosFileString(char *fileString
, int *length
,
550 char *outPtr
= fileString
;
551 char *inPtr
= fileString
;
552 if (pendingCR
) *pendingCR
= 0;
553 while (inPtr
< fileString
+ *length
) {
554 if (*inPtr
== '\r') {
555 if (inPtr
< fileString
+ *length
- 1) {
556 if (*(inPtr
+ 1) == '\n')
561 break; /* Don't copy this trailing '\r' */
565 *outPtr
++ = *inPtr
++;
568 *length
= outPtr
- fileString
;
570 void ConvertFromMacFileString(char *fileString
, int length
)
572 char *inPtr
= fileString
;
573 while (inPtr
< fileString
+ length
) {
581 ** Converts a string (which may represent the entire contents of the file) from
582 ** Unix to DOS format. String is re-allocated (with malloc), and length is
583 ** modified. If allocation fails, which it may, because this can potentially
584 ** be a huge hunk of memory, returns FALSE and no conversion is done.
586 ** This could be done more efficiently by asking doSave to allocate some
587 ** extra memory for this, and only re-allocating if it wasn't enough. If
588 ** anyone cares about the performance or the potential for running out of
589 ** memory on a save, it should probably be redone.
591 int ConvertToDosFileString(char **fileString
, int *length
)
593 char *outPtr
, *outString
;
594 char *inPtr
= *fileString
;
595 int inLength
= *length
;
598 /* How long a string will we need? */
599 while (inPtr
< *fileString
+ inLength
) {
606 /* Allocate the new string */
607 outString
= XtMalloc(outLength
+ 1);
608 if (outString
== NULL
)
611 /* Do the conversion, free the old string */
614 while (inPtr
< *fileString
+ inLength
) {
617 *outPtr
++ = *inPtr
++;
621 *fileString
= outString
;
627 ** Converts a string (which may represent the entire contents of the file)
628 ** from Unix to Macintosh format.
630 void ConvertToMacFileString(char *fileString
, int length
)
632 char *inPtr
= fileString
;
634 while (inPtr
< fileString
+ length
) {
642 ** Reads a text file into a string buffer, converting line breaks to
643 ** unix-style if appropriate.
645 char *ReadAnyTextFile(const char *fileName
)
649 int fileLen
, readLen
;
653 /* Read the whole file into fileString */
654 if ((fp
= fopen(fileName
, "r")) == NULL
) {
657 if (fstat(fileno(fp
), &statbuf
) != 0) {
661 fileLen
= statbuf
.st_size
;
662 fileString
= XtMalloc(fileLen
+1); /* +1 = space for null */
663 readLen
= fread(fileString
, sizeof(char), fileLen
, fp
);
670 fileString
[readLen
] = 0;
672 /* Convert linebreaks? */
673 format
= FormatOfFile(fileString
);
674 if (format
== DOS_FILE_FORMAT
){
676 ConvertFromDosFileString(fileString
, &readLen
, &pendingCR
);
677 } else if (format
== MAC_FILE_FORMAT
){
678 ConvertFromMacFileString(fileString
, readLen
);