1 /*
2 * IO layer : handles for URIs
3 *
4 * Authors:
5 * Johan Ceuppens <jceuppen at easynet dot be>
6 *
7 * Copyright (C) 2004 Johan Ceuppens
8 *
9 * Released under GNU LGPL, read the file 'COPYING.LIB' for more information
10 */
12 #include "streams-handles.h"
13 #include "uri.h"
15 #include <iostream>
17 namespace Inkscape {
19 /**
20 * FileHandle
21 */
23 int FileHandle::open(URI const& uri, char const* mode)
24 {
25 if (sys_open(uri, mode) == 0)
26 return 0;
27 else
28 return 1;
29 }
31 FILE *FileHandle::sys_open(URI const& uri, char const* mode)
32 {
33 gchar *filename = uri.toNativeFilename();
35 if ((fp = std::fopen(filename, mode)) == 0) {
36 error("fopen");
37 }
38 #ifdef DEBUG_STREAMS
39 std::cout<<"file opened fp="<<fp<<std::endl;
40 #endif
41 return fp;
42 }
44 void FileHandle::close()
45 {
46 sys_close();
47 }
49 void FileHandle::sys_close()
50 {
51 fclose(fp);
52 }
54 int FileHandle::read(void *buf, int buflen)
55 {
56 return sys_read(buf, buflen);
57 }
59 int FileHandle::sys_read (void *buf, int buflen) throw(ReadException)
60 {
61 int nbytes = 0;
62 if ((nbytes = std::fread(buf, 1, buflen, fp)) < 0) {
63 if (ferror(fp)) {
64 error("fread");
65 throw ReadException();
66 }
67 }
68 if (nbytes == 0)
69 return EOF;
70 else
71 return nbytes;
72 }
74 int FileHandle::write (void const *buf, int buflen)
75 {
76 return sys_write(buf, buflen);
77 }
79 int FileHandle::sys_write (void const *buf, int buflen) throw(WriteException)
80 {
81 int nbytes = 0;
82 if ((nbytes = std::fwrite(buf, 1, buflen, fp)) < 0) {
83 error("fwrite");
84 throw WriteException();
85 }
87 return nbytes;
88 }
90 int FileHandle::seek(long offset, int whence)
91 {
92 return sys_seek(offset, whence);
93 }
95 int FileHandle::sys_seek(long offset, int whence)
96 {
97 int result;
98 if ((result = fseek(fp, offset, whence)) < 0) {
99 error("fseek");
100 }
101 return result;
102 }
103 void FileHandle::error(char const *errstr)
104 {
105 std::cerr<<"error FileHandle: "<<errstr<<std::endl;
106 }
108 } // namespace Inkscape
110 /*
111 Local Variables:
112 mode:c++
113 c-file-style:"stroustrup"
114 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
115 indent-tabs-mode:nil
116 fill-column:99
117 End:
118 */
119 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :