1 /* util.{cc,hh} -- various bits
2  *
3  * Copyright (c) 2003-2010 Eddie Kohler
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License as published by the Free
7  * Software Foundation; either version 2 of the License, or (at your option)
8  * any later version. This program is distributed in the hope that it will be
9  * useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
11  * Public License for more details.
12  */
13 
14 #ifdef HAVE_CONFIG_H
15 # include <config.h>
16 #endif
17 #include "util.hh"
18 #include <lcdf/error.hh>
19 #include <lcdf/straccum.hh>
20 #include <lcdf/vector.hh>
21 #include <stdio.h>
22 #include <errno.h>
23 #include <stdlib.h>
24 #if defined(_MSDOS) || defined(_WIN32)
25 # include <fcntl.h>
26 # include <io.h>
27 #endif
28 
29 String
read_file(String filename,ErrorHandler * errh,bool warning)30 read_file(String filename, ErrorHandler *errh, bool warning)
31 {
32     FILE *f;
33     if (!filename || filename == "-") {
34 	filename = "<stdin>";
35 	f = stdin;
36 #if defined(_MSDOS) || defined(_WIN32)
37 	// Set the file mode to binary
38 	_setmode(_fileno(f), _O_BINARY);
39 #endif
40     } else if (!(f = fopen(filename.c_str(), "rb"))) {
41 	errh->xmessage((warning ? errh->e_warning : errh->e_error) + ErrorHandler::make_landmark_anno(filename), strerror(errno));
42 	return String();
43     }
44 
45     StringAccum sa;
46     int amt;
47     do {
48 	if (char *x = sa.reserve(8192)) {
49 	    amt = fread(x, 1, 8192, f);
50 	    sa.adjust_length(amt);
51 	} else
52 	    amt = 0;
53     } while (amt != 0);
54     if (!feof(f) || ferror(f))
55 	errh->xmessage((warning ? errh->e_warning : errh->e_error) + ErrorHandler::make_landmark_anno(filename), strerror(errno));
56     if (f != stdin)
57 	fclose(f);
58     return sa.take_string();
59 }
60 
61 String
printable_filename(const String & s)62 printable_filename(const String &s)
63 {
64     if (!s || s == "-")
65 	return String::make_stable("<stdin>");
66     else
67 	return s;
68 }
69 
70 String
pathname_filename(const String & path)71 pathname_filename(const String &path)
72 {
73     int slash = path.find_right('/');
74     if (slash >= 0 && slash != path.length() - 1)
75 	return path.substring(slash + 1);
76     else
77 	return path;
78 }
79