Debian Codegraph @

3rdparty/xspublic/xstypes/xsfile.c

raw
1
2 // Copyright (c) 2003-2019 Xsens Technologies B.V. or subsidiaries worldwide.
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without modification,
6 // are permitted provided that the following conditions are met:
7 //
8 // 1. Redistributions of source code must retain the above copyright notice,
9 // this list of conditions, and the following disclaimer.
10 //
11 // 2. Redistributions in binary form must reproduce the above copyright notice,
12 // this list of conditions, and the following disclaimer in the documentation
13 // and/or other materials provided with the distribution.
14 //
15 // 3. Neither the names of the copyright holders nor the names of their contributors
16 // may be used to endorse or promote products derived from this software without
17 // specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
20 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
21 // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
22 // THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 // SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
24 // OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY OR
26 // TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.THE LAWS OF THE NETHERLANDS
28 // SHALL BE EXCLUSIVELY APPLICABLE AND ANY DISPUTES SHALL BE FINALLY SETTLED UNDER THE RULES
29 // OF ARBITRATION OF THE INTERNATIONAL CHAMBER OF COMMERCE IN THE HAGUE BY ONE OR MORE
30 // ARBITRATORS APPOINTED IN ACCORDANCE WITH SAID RULES.
31 //
32
33 #include "xsfile.h"
34 #include "xsstring.h"
35 #include <errno.h>
36 #ifndef _WIN32
37 # include <unistd.h> // close
38 # include <sys/ioctl.h> // ioctl
39 # include <fcntl.h> // open, O_RDWR
40 # include <string.h> // strcpy
41 # include <sys/param.h>
42 # include <sys/stat.h>
43 # include <stdarg.h>
44 # include <stdlib.h>
45 #else
46 # include <winbase.h>
47 # include <sys/stat.h>
48 # include <io.h>
49 #endif
50
51 // helper
52 static FILE* openFile(const struct XsString* filename, const struct XsString* mode);
53
54 /*! \class XsFile
55 \brief Encapsulates a file, providing a platform independent interface
56 */
57 /*! \addtogroup cinterface C Interface
58 @{
59 */
60
61
62 /*! \relates XsFile
63 \brief Frees the resources of this object by closing the file if it is open.
64 */
65 void XsFile_destruct(struct XsFile* thisPtr)
66 {
67 if (thisPtr->m_handle != NULL)
68 {
69 (void)XsFile_close(thisPtr);
70 }
71 }
72
73 /*! \relates XsFile
74 \brief Creates a new binary file with name \a filename, contents of existing files will be discarded
75 \param filename name of the file to create
76 \param writeOnly passing 0 will create the file using "w+b", any other value will create it using "wb"
77 \returns XRV_OK if the file was opened, an error otherwise
78 */
79 XsResultValue XsFile_create(struct XsFile *thisPtr, const struct XsString* filename, int writeOnly)
80 {
81 XsString mode;
82 XsString_construct(&mode);
83 XsString_resize(&mode, 16);
84
85 if (thisPtr->m_handle != NULL)
86 return XRV_ALREADYOPEN;
87
88 #ifdef _WIN32
89 wchar_t filenameW[XS_MAX_FILENAME_LENGTH];
90 // actively delete the file first to ensure that the file creation time is properly set
91 XsString_copyToWCharArray(filename, filenameW, XS_MAX_FILENAME_LENGTH);
92 (void) _wunlink(filenameW); // don't care about return value
93 #else
94 unlink(filename->m_data);
95 #endif
96
97 if (writeOnly)
98 {
99 XsString_assign(&mode, 3, "wb");
100 thisPtr->m_handle = openFile(filename, &mode);
101 }
102 else
103 {
104 XsString_assign(&mode, 4, "w+b");
105 thisPtr->m_handle = openFile(filename, &mode);
106 }
107
108 XsString_destruct(&mode);
109 if (thisPtr->m_handle == NULL)
110 return XRV_OUTPUTCANNOTBEOPENED;
111 else
112 return XRV_OK;
113 }
114
115 /*! \relates XsFile
116 \brief Creates a new text file with name \a filename, contents of existing files will be discarded
117 \param filename name of the file to create
118 \param writeOnly passing 0 will create the file using "w+t", any other value will create it using "wt"
119 \returns XRV_OK if the file was opened, an error otherwise
120 */
121 XsResultValue XsFile_createText(struct XsFile *thisPtr, const struct XsString* filename, int writeOnly)
122 {
123 XsString mode;
124 XsString_construct(&mode);
125 XsString_resize(&mode, 16);
126
127 if (thisPtr->m_handle != NULL)
128 return XRV_ALREADYOPEN;
129
130 if (writeOnly)
131 {
132 XsString_assign(&mode, 3, "wt");
133 thisPtr->m_handle = openFile(filename, &mode);
134 }
135 else
136 {
137 XsString_assign(&mode, 4, "w+t");
138 thisPtr->m_handle = openFile(filename, &mode);
139 }
140
141 XsString_destruct(&mode);
142 if (thisPtr->m_handle == NULL)
143 return XRV_OUTPUTCANNOTBEOPENED;
144 else
145 return XRV_OK;
146 }
147
148 /*! \relates XsFile
149 \brief Opens an existing binary file with name \a filename
150 \param filename name of the file to open
151 \param readOnly passing 0 will open the file "r+b" (read/update), any other value will create it using "rb" (read)
152 \returns XRV_OK if the file was opened, an error otherwise
153 */
154 XsResultValue XsFile_open(struct XsFile *thisPtr, const struct XsString* filename, int readOnly)
155 {
156 XsString mode;
157 XsString_construct(&mode);
158 XsString_resize(&mode, 16);
159
160 if (thisPtr->m_handle != NULL)
161 return XRV_ALREADYOPEN;
162
163 if (readOnly)
164 {
165 XsString_assign(&mode, 3, "rb");
166 thisPtr->m_handle = openFile(filename, &mode);
167 }
168 else
169 {
170 XsString_assign(&mode, 4, "r+b");
171 thisPtr->m_handle = openFile(filename, &mode);
172 }
173
174 XsString_destruct(&mode);
175 if (thisPtr->m_handle == NULL)
176 return XRV_OUTPUTCANNOTBEOPENED;
177 else
178 return XRV_OK;
179 }
180
181 /*! \relates XsFile
182 \brief Opens an existing binary file with name \a filename
183 \param filename name of the file to open
184 \param readOnly passing 0 will open the file "r+t" (read/update), any other value will create it using "rt" (read)
185 \returns XRV_OK if the file was opened, an error otherwise
186 */
187 XsResultValue XsFile_openText(struct XsFile *thisPtr, const struct XsString* filename, int readOnly)
188 {
189 XsString mode;
190 XsString_construct(&mode);
191 XsString_resize(&mode, 16);
192
193 if (thisPtr->m_handle != NULL)
194 return XRV_ALREADYOPEN;
195
196 if (readOnly)
197 {
198 XsString_assign(&mode, 3, "rt");
199 thisPtr->m_handle = openFile(filename, &mode);
200 }
201 else
202 {
203 XsString_assign(&mode, 4, "r+t");
204 thisPtr->m_handle = openFile(filename, &mode);
205 }
206
207 XsString_destruct(&mode);
208 if (thisPtr->m_handle == NULL)
209 return XRV_OUTPUTCANNOTBEOPENED;
210 else
211 return XRV_OK;
212 }
213
214 /*! \brief Helper for file opening */
215 static FILE* openFile(const struct XsString* filename, const struct XsString* mode)
216 {
217 #ifdef _WIN32
218 wchar_t filenameW[XS_MAX_FILENAME_LENGTH];
219 wchar_t modeW[16];
220 (void)XsString_copyToWCharArray(filename, filenameW, XS_MAX_FILENAME_LENGTH);
221 (void)XsString_copyToWCharArray(mode, modeW, 16);
222
223 __try
224 {
225 return _wfopen(filenameW, modeW);
226 }
227 __except(EXCEPTION_EXECUTE_HANDLER)
228 {
229 return NULL;
230 }
231 #else
232 return fopen(filename->m_data, mode->m_data);
233 #endif
234 }
235
236 /*! \relates XsFile
237 \brief Reopens a file
238 \param filename Name of the file to open after the current one has been closed
239 \param mode Mode to reopen the file with
240 \returns 0 if a file is open, another value otherwise
241 */
242 XsResultValue XsFile_reopen(struct XsFile *thisPtr, const struct XsString* filename, const struct XsString* mode)
243 {
244 #ifdef _WIN32
245 wchar_t filenameW[XS_MAX_FILENAME_LENGTH];
246 wchar_t modeW[16];
247
248 (void)XsString_copyToWCharArray(filename, filenameW, XS_MAX_FILENAME_LENGTH);
249 (void)XsString_copyToWCharArray(mode, modeW, 16);
250
251 thisPtr->m_handle = _wfreopen(filenameW, modeW, thisPtr->m_handle);
252 #else
253 thisPtr->m_handle = freopen(filename->m_data, mode->m_data, thisPtr->m_handle);
254 #endif
255
256 if (thisPtr->m_handle == NULL)
257 return XRV_OUTPUTCANNOTBEOPENED;
258 else
259 return XRV_OK;
260 }
261
262 /*! \relates XsFile
263 \brief Checks if a file is open
264 \returns 0 if a file is open, another value otherwise
265 */
266 int XsFile_isOpen(const struct XsFile *thisPtr)
267 {
268 return (thisPtr->m_handle != NULL) ? 0 : 1;
269 }
270
271 /*! \relates XsFile
272 \brief Checks if the file exists (can be accessed)
273 \param filename Name of the file to check for existence
274 \returns 0 if the file exists, another value otherwise
275 */
276 int XsFile_exists(const struct XsString* filename)
277 {
278 #ifdef _WIN32
279 wchar_t filenameW[XS_MAX_FILENAME_LENGTH];
280 struct _stat buffer;
281 (void)XsString_copyToWCharArray(filename, filenameW, XS_MAX_FILENAME_LENGTH);
282 return _wstat(filenameW, &buffer);
283 #else
284 struct stat buffer;
285 return stat(filename->m_data, &buffer);
286 #endif
287 }
288
289 /*! \relates XsFile
290 \brief Closes the file
291 \returns XRV_OK if the file was closed properly, XRV_ENDOFFILE otherwise
292 */
293 XsResultValue XsFile_close(struct XsFile *thisPtr)
294 {
295 int rv;
296
297 if (thisPtr->m_handle == NULL)
298 return XRV_NOFILEOPEN;
299
300 fflush(thisPtr->m_handle); // always try to flush first, result is irrelevant
301 rv = fclose(thisPtr->m_handle);
302
303 // Or keep the handle in case of failure?
304 thisPtr->m_handle = NULL;
305
306 if (rv == EOF)
307 return XRV_ENDOFFILE;
308 else
309 return XRV_OK;
310 }
311
312
313 /*! \relates XsFile
314 \brief Writes unwritten data to the file
315 \returns XRV_OK if the flushing was successful, an XRV_ERROR otherwise
316
317 */
318 XsResultValue XsFile_flush(struct XsFile *thisPtr)
319 {
320 return fflush(thisPtr->m_handle) ? XRV_ERROR : XRV_OK;
321 }
322
323 /*! \relates XsFile
324 \brief Reduces the file to a maximum size of \a fileSize bytes
325 \param fileSize The new size for the file
326 \returns XRV_OK if the file was truncated, an error otherwise
327 */
328 XsResultValue XsFile_truncate(struct XsFile *thisPtr, XsFilePos fileSize)
329 {
330 return XsFile_resize(thisPtr, fileSize);
331 }
332
333 /*! \relates XsFile
334 \brief Resizes the file to \a fileSize bytes
335 \param fileSize The new size for the file
336 \returns XRV_OK if the file was resized, an error otherwise
337 */
338 XsResultValue XsFile_resize(struct XsFile *thisPtr, XsFilePos fileSize)
339 {
340 #ifdef _WIN32
341 int rv = _chsize_s(_fileno(thisPtr->m_handle), fileSize);
342 #else
343 int rv = ftruncate(fileno(thisPtr->m_handle), fileSize);
344 #endif
345 if (rv != 0)
346 {
347 switch(errno)
348 {
349 case EACCES:
350 return XRV_BUSY;
351 case EBADF:
352 return XRV_ACCESSDENIED;
353 case ENOSPC:
354 return XRV_OUTOFMEMORY;
355 case EINVAL:
356 return XRV_INVALIDPARAM;
357 default:
358 return XRV_ERROR;
359 }
360 }
361 else
362 return XRV_OK;
363 }
364
365 /*! \relates XsFile
366 \brief Deletes a file with name \a filename
367 \param filename Name of the file to delete
368 \returns XRV_OK if the file was erased, an error otherwise
369 */
370 XsResultValue XsFile_erase(const struct XsString* filename)
371 {
372 #ifdef _WIN32
373 wchar_t filenameW[XS_MAX_FILENAME_LENGTH];
374 (void)XsString_copyToWCharArray(filename, filenameW, XS_MAX_FILENAME_LENGTH);
375 if (_wunlink(filenameW) != 0)
376 #else
377 if (unlink(filename->m_data) != 0)
378 #endif
379 {
380 switch (errno)
381 {
382 case EACCES:
383 return XRV_READONLY;
384 case ENOENT:
385 return XRV_NOTFOUND;
386 default:
387 return XRV_ERROR;
388 }
389 }
390 else
391 return XRV_OK;
392 }
393
394 /*! \relates XsFile
395 \brief Reads a number of elements from a file
396 \param destination Buffer to store the read data in
397 \param size Size of each individual element to read
398 \param count Number of elements to read
399 \returns Total number of elements successfully read
400 */
401 XsFilePos XsFile_read(struct XsFile *thisPtr, void *destination, XsFilePos size, XsFilePos count)
402 {
403 return (XsFilePos) fread(destination, (size_t) size, (size_t) count, thisPtr->m_handle);
404 }
405
406 /*! \relates XsFile
407 \brief Writes a number of elements to a file
408 \param source Buffer that contains the elements to be written
409 \param size Size of each individual element to write
410 \param count Number of elements to write
411 \returns Total number of elements successfully written
412 */
413 XsFilePos XsFile_write(struct XsFile *thisPtr, const void *source, XsFilePos size, XsFilePos count)
414 {
415 return (XsFilePos) fwrite(source, (size_t) size, (size_t) count, thisPtr->m_handle);
416 }
417
418 /*! \relates XsFile
419 \brief Gets and returns the next byte from a file
420 \returns The byte read from the stream or -1 in case of failure
421 */
422 int XsFile_getc(struct XsFile *thisPtr)
423 {
424 return fgetc(thisPtr->m_handle);
425 }
426
427 /*! \relates XsFile
428 \brief Writes a character to the file
429 \param character The caharacter to write
430 \returns XRV_OK on success, XRV_ERROR otehrwise
431 */
432 XsResultValue XsFile_putc(struct XsFile *thisPtr, int character)
433 {
434 return fputc(character, thisPtr->m_handle) == EOF ? XRV_ERROR : XRV_OK;
435 }
436
437 /*! \relates XsFile
438 \brief Reads characters from this file and stores them into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
439 \param str The destination for the read string
440 \param num The size of the destination buffer
441 \returns A pointer to the read string on success, NULL on failure
442 */
443 char* XsFile_gets(struct XsFile *thisPtr, char *str, int num)
444 {
445 return fgets(str, num, thisPtr->m_handle);
446 }
447
448 /*! \relates XsFile
449 \brief Writes a null terminated c-string to the file
450 \param str The null terminated c-string to write
451 \returns XRV_OK on success, XRV_ERROR otehrwise
452 */
453 XsResultValue XsFile_puts(struct XsFile *thisPtr, const char *str)
454 {
455 return fputs(str, thisPtr->m_handle) != EOF ? XRV_OK : XRV_ERROR;
456 }
457
458 /*! \relates XsFile
459 \brief Moves the current file position relative to the start of the file
460 \param offset Position in the file to move to, relative to the start of the file
461 \returns XRV_OK if the seek was successful
462 */
463 XsResultValue XsFile_seek(struct XsFile *thisPtr, XsFilePos offset)
464 {
465 #ifdef _WIN32
466 return _fseeki64(thisPtr->m_handle, offset, SEEK_SET) ? XRV_ERROR : XRV_OK;
467 #else
468 return fseeko(thisPtr->m_handle, offset, SEEK_SET) ? XRV_ERROR : XRV_OK;
469 #endif
470 }
471
472 /*! \relates XsFile
473 \brief Moves the current file position relative to the end of the file
474 \param offset Position in the file to move to, relative to the end of the file
475 \returns XRV_OK if the seek was successful
476 */
477 XsResultValue XsFile_seek_r(struct XsFile *thisPtr, XsFilePos offset)
478 {
479 #ifdef _WIN32
480 return _fseeki64(thisPtr->m_handle, offset, SEEK_END) ? XRV_ERROR : XRV_OK;
481 #else
482 return fseeko(thisPtr->m_handle, offset, SEEK_END) ? XRV_ERROR : XRV_OK;
483 #endif
484 }
485
486 /*! \relates XsFile
487 \brief Returns the current position in the file
488 \returns Current position in the current file
489 */
490 XsFilePos XsFile_tell(struct XsFile const* thisPtr)
491 {
492 #ifdef _WIN32
493 return _ftelli64(thisPtr->m_handle);
494 #else
495 return ftello(thisPtr->m_handle);
496 #endif
497 }
498
499 /*! \relates XsFile
500 \returns Returns 0 if the current file position is not 'end of file', non 0 if the position is 'end of file'
501 */
502 int XsFile_eof(struct XsFile const* thisPtr)
503 {
504 return feof(thisPtr->m_handle);
505 }
506
507 /*! \relates XsFile
508 \returns Returns XRV_ERROR if the error flag for the file has been set, XRV_OK otherwise
509 */
510 XsResultValue XsFile_error(struct XsFile const* thisPtr)
511 {
512 return ferror(thisPtr->m_handle) ? XRV_ERROR : XRV_OK;
513 }
514
515 /*! \relates XsFile
516 \brief Retrieves the full path for a filename
517 \param[in] filename The filename to expand
518 \param[out] fullPath The filename with a fully expanded path is returned in this parameter. This parameter must be allocated by the caller.
519 \returns XRV_OK if the fullpath could be retrieved, XRV_NULLPTR if fullPath is NULL, XRV_ERROR otherwise
520 */
521 XsResultValue XsFile_fullPath(const struct XsString* filename, struct XsString* fullPath)
522 {
523 XsResultValue result = XRV_OK;
524 if (fullPath == NULL)
525 {
526 result = XRV_NULLPTR;
527 }
528 else
529 {
530 #ifdef _WIN32
531 wchar_t filenamew[XS_MAX_FILENAME_LENGTH];
532 wchar_t fullpath[XS_MAX_FILENAME_LENGTH];
533 (void)XsString_copyToWCharArray(filename, filenamew, XS_MAX_FILENAME_LENGTH);
534
535 if (_wfullpath(fullpath, filenamew, XS_MAX_FILENAME_LENGTH) == NULL)
536 result = XRV_ERROR;
537 else
538 XsString_assignWCharArray(fullPath, fullpath);
539 #else
540 // based on the assumption that this doesn't concern the serial port, handle
541 // it the same way using realpath(). Apparently realpath() doesn't require a
542 // maximum length. One would possibly want to write a wrapper for it.
543 char fullpath[XS_MAX_FILENAME_LENGTH*2];
544 if (realpath(filename->m_data, fullpath) == NULL)
545 result = XRV_ERROR;
546 else
547 XsString_assignCharArray(fullPath, fullpath);
548 #endif
549 }
550 return result;
551 }
552
553 /*! \relates XsFile
554 \brief Reads a full line from the file
555 \param line The result of the read
556 \returns XRV_OK if a line could be read
557 */
558 XsResultValue XsFile_getline(struct XsFile *thisPtr, struct XsString *line)
559 {
560 int b;
561 XsResultValue ok = XRV_ENDOFFILE;
562
563 XsString_erase(line, 0, line->m_size);
564 XsArray_reserve(line, 256);
565
566 b = fgetc(thisPtr->m_handle);
567 if (b != -1)
568 ok = XRV_OK;
569
570 while (b != -1)
571 {
572 XsString_push_back(line, (char)b);
573 if (b == '\n')
574 break;
575 b = fgetc(thisPtr->m_handle);
576 }
577 return ok;
578 }
579
580 /*! \relates XsFile
581 \returns The file handle
582 */
583 FILE* XsFile_handle(struct XsFile *thisPtr)
584 {
585 return thisPtr->m_handle;
586 }
587
588 /*! @} */