]> git.donarmstrong.com Git - lilypond.git/blob - lib/simple-file-storage.cc
e7c9240b00b7226651058a85f04dd30e60a6bfe9
[lilypond.git] / lib / simple-file-storage.cc
1 /*
2   simple-file-storage.cc -- implement Simple_file_storage
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1997 Han-Wen Nienhuys <hanwen@stack.nl>
7 */
8
9 #include <stdio.h>
10
11 #include "simple-file-storage.hh"
12 #include "varray.hh"
13 #include "string.hh"
14 #include "warn.hh"
15
16 void
17 Simple_file_storage::load_stdin ()
18 {
19   int data_len = 0;
20   len_i_ = 0;
21
22   int c;
23   Array<char> ch_arr;
24   while ((c = fgetc (stdin)) != EOF)
25     ch_arr.push (c);
26   len_i_ = ch_arr.size ();
27   data_p_ = ch_arr.remove_array_p ();
28 }
29
30 void
31 Simple_file_storage::load_file (String s)
32 {
33   /*
34     let's hope that "b" opens anything binary, and does not apply
35     CR/LF translation
36     */
37   FILE * f =  fopen (s.ch_C (), "rb");
38
39   if (!f)
40     {
41       warning (_ ("can't open file `") + s + "'");
42       return ;
43     }
44
45   int ret = fseek (f, 0, SEEK_END);
46   len_i_ = ftell (f);
47   rewind (f);
48   data_p_ = new char[len_i_+1];
49   data_p_[len_i_] = 0;
50   ret = fread (data_p_, sizeof (char), len_i_, f);
51
52   if  (ret!=len_i_)
53     warning (_ ("Huh? got ") + String (ret) + _ (", expected ")
54              + String (len_i_) + _ (" characters"));
55
56   fclose (f);
57 }
58
59 /**
60   Stupid but foolproof way of opening files.
61
62   TODO
63   Should check IO status
64
65   This is of course a build it yourself version of mmap, so we should
66   have been using that... (see Mapped_file_storage) But we noticed
67   some problems with this (unexplained lexer crashes)
68
69   [Some versions later] The crashes aren't caused by the mmap
70   code. But no reason to take it out, is there?  mmap ()
71
72 */
73
74 Simple_file_storage::Simple_file_storage (String s)
75 {
76   data_p_ = 0;
77   len_i_ = 0;
78
79   if (!s.length_i ())
80     load_stdin ();
81   else
82     load_file (s);
83 }
84
85 char const*
86 Simple_file_storage::ch_C () const
87 {
88   return data_p_;
89 }
90
91 int
92 Simple_file_storage::length_i () const
93 {
94   return len_i_;
95 }
96
97
98 Simple_file_storage::~Simple_file_storage ()
99 {
100   delete []data_p_;
101 }