ab4dbd49d626adf31676a15bb262297571ef5993
[external/alsa-utils.git] / alsactl / utils.c
1 /*
2  *  Advanced Linux Sound Architecture Control Program - Support routines
3  *  Copyright (c) by Jaroslav Kysela <perex@perex.cz>
4  *
5  *
6  *   This program is free software; you can redistribute it and/or modify
7  *   it under the terms of the GNU General Public License as published by
8  *   the Free Software Foundation; either version 2 of the License, or
9  *   (at your option) any later version.
10  *
11  *   This program is distributed in the hope that it will be useful,
12  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
13  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  *   GNU General Public License for more details.
15  *
16  *   You should have received a copy of the GNU General Public License
17  *   along with this program; if not, write to the Free Software
18  *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19  *
20  */
21
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <stddef.h>
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <errno.h>
28 #include <ctype.h>
29 #include <dirent.h>
30 #include <sys/stat.h>
31 #include <sys/mman.h>
32
33 #include <alsa/asoundlib.h>
34 #include "alsactl.h"
35
36 int file_map(const char *filename, char **buf, size_t *bufsize)
37 {
38         struct stat stats;
39         int fd;
40
41         fd = open(filename, O_RDONLY);
42         if (fd < 0) {
43                 return -1;
44         }
45
46         if (fstat(fd, &stats) < 0) {
47                 close(fd);
48                 return -1;
49         }
50
51         *buf = mmap(NULL, stats.st_size, PROT_READ, MAP_SHARED, fd, 0);
52         if (*buf == MAP_FAILED) {
53                 close(fd);
54                 return -1;
55         }
56         *bufsize = stats.st_size;
57
58         close(fd);
59
60         return 0;
61 }
62
63 void file_unmap(void *buf, size_t bufsize)
64 {
65         munmap(buf, bufsize);
66 }
67
68 size_t line_width(const char *buf, size_t bufsize, size_t pos)
69 {
70         int esc = 0;
71         size_t count;
72         
73         for (count = pos; count < bufsize; count++) {
74                 if (!esc && buf[count] == '\n')
75                         break;
76                 esc = buf[count] == '\\';
77         }
78
79         return count - pos;
80 }
81
82 void initfailed(int cardnumber, const char *reason)
83 {
84         int fp;
85         char *str;
86
87         if (statefile == NULL)
88                 return;
89         if (snd_card_get_name(cardnumber, &str) < 0)
90                 return;
91         fp = open(statefile, O_WRONLY|O_CREAT|O_APPEND, 0644);
92         write(fp, str, strlen(str));
93         write(fp, ":", 1);
94         write(fp, reason, strlen(reason));
95         write(fp, "\n", 1);
96         close(fp);
97         free(str);
98 }