Imported Upstream version 3.0
[debian/gnuradio] / gnuradio-core / src / lib / runtime / gr_preferences.cc
1 /* -*- c++ -*- */
2 /*
3  * Copyright 2003 Free Software Foundation, Inc.
4  * 
5  * This file is part of GNU Radio
6  * 
7  * GNU Radio is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation; either version 2, or (at your option)
10  * any later version.
11  * 
12  * GNU Radio is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with GNU Radio; see the file COPYING.  If not, write to
19  * the Free Software Foundation, Inc., 51 Franklin Street,
20  * Boston, MA 02110-1301, USA.
21  */
22
23 #ifdef HAVE_CONFIG_H
24 #include "config.h"
25 #endif
26
27 #include <gr_preferences.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <unistd.h>
34
35
36 #ifdef MKDIR_TAKES_ONE_ARG
37 #define gr_mkdir(pathname, mode) mkdir(pathname)
38 #else
39 #define gr_mkdir(pathname, mode) mkdir((pathname), (mode))
40 #endif
41
42 /*
43  * The simplest thing that could possibly work:
44  *  the key is the filename; the value is the file contents.
45  */
46
47 static const char *
48 pathname (const char *key)
49 {
50   static char buf[200];
51   snprintf (buf, sizeof (buf), "%s/.gnuradio/prefs/%s", getenv ("HOME"), key);
52   return buf;
53 }
54
55 static void
56 ensure_dir_path ()
57 {
58   char path[200];
59   struct stat   statbuf;
60
61   snprintf (path, sizeof (path), "%s/.gnuradio/prefs", getenv ("HOME"));
62   if (stat (path, &statbuf) == 0 && S_ISDIR (statbuf.st_mode))
63     return;
64
65   // blindly try to make it     // FIXME make this robust. C++ SUCKS!
66
67   snprintf (path, sizeof (path), "%s/.gnuradio", getenv ("HOME"));
68   gr_mkdir (path, 0750);
69   snprintf (path, sizeof (path), "%s/.gnuradio/prefs", getenv ("HOME"));
70   gr_mkdir (path, 0750);
71 }
72
73 const char *
74 gr_preferences::get (const char *key)
75 {
76   static char buf[1024];
77
78   FILE  *fp = fopen (pathname (key), "r");
79   if (fp == 0)
80     return 0;
81
82   memset (buf, 0, sizeof (buf));
83   fread (buf, 1, sizeof (buf) - 1, fp);
84   fclose (fp);
85   return buf;
86 }
87
88 void 
89 gr_preferences::set (const char *key, const char *value)
90 {
91   ensure_dir_path ();
92
93   FILE *fp = fopen (pathname (key), "w");
94   if (fp == 0){
95     perror (pathname (key));
96     return;
97   }
98
99   fwrite (value, 1, strlen (value), fp);
100   fclose (fp);
101 };