src/util/vfs.c (view raw)
1/* Copyright (c) 2013-2015 Jeffrey Pfau
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6#include "vfs.h"
7
8#ifdef PSP2
9#include "platform/psp2/sce-vfs.h"
10#endif
11
12struct VFile* VFileOpen(const char* path, int flags) {
13#ifdef USE_VFS_FILE
14 const char* chflags;
15 switch (flags & O_ACCMODE) {
16 case O_WRONLY:
17 if (flags & O_APPEND) {
18 chflags = "ab";
19 } else {
20 chflags = "wb";
21 }
22 break;
23 case O_RDWR:
24 if (flags & O_APPEND) {
25 chflags = "a+b";
26 } else if (flags & O_TRUNC) {
27 chflags = "w+b";
28 } else {
29 chflags = "r+b";
30 }
31 break;
32 case O_RDONLY:
33 chflags = "rb";
34 break;
35 }
36 return VFileFOpen(path, chflags);
37#elif defined(PSP2)
38 return VFileOpenSce(path, flags, 0666);
39#else
40 return VFileOpenFD(path, flags);
41#endif
42}
43
44ssize_t VFileReadline(struct VFile* vf, char* buffer, size_t size) {
45 size_t bytesRead = 0;
46 while (bytesRead < size - 1) {
47 ssize_t newRead = vf->read(vf, &buffer[bytesRead], 1);
48 if (newRead <= 0) {
49 break;
50 }
51 bytesRead += newRead;
52 if (buffer[bytesRead] == '\n') {
53 break;
54 }
55 }
56 buffer[bytesRead] = '\0';
57 return bytesRead;
58}
59
60ssize_t VFileWrite32LE(struct VFile* vf, int32_t word) {
61 uint32_t leword;
62 STORE_32LE(word, 0, &leword);
63 return vf->write(vf, &leword, 4);
64}
65
66ssize_t VFileWrite16LE(struct VFile* vf, int16_t hword) {
67 uint16_t lehword;
68 STORE_16LE(hword, 0, &lehword);
69 return vf->write(vf, &lehword, 2);
70}
71
72ssize_t VFileRead32LE(struct VFile* vf, void* word) {
73 uint32_t leword;
74 ssize_t r = vf->read(vf, &leword, 4);
75 if (r == 4) {
76 STORE_32LE(leword, 0, word);
77 }
78 return r;
79}
80
81ssize_t VFileRead16LE(struct VFile* vf, void* hword) {
82 uint16_t lehword;
83 ssize_t r = vf->read(vf, &lehword, 2);
84 if (r == 2) {
85 STORE_16LE(lehword, 0, hword);
86 }
87 return r;
88}
89
90struct VFile* VDirOptionalOpenFile(struct VDir* dir, const char* realPath, const char* prefix, const char* suffix, int mode) {
91 char path[PATH_MAX];
92 path[PATH_MAX - 1] = '\0';
93 struct VFile* vf;
94 if (!dir) {
95 if (!realPath) {
96 return 0;
97 }
98 char* dotPoint = strrchr(realPath, '.');
99 if (dotPoint - realPath + 1 >= PATH_MAX - 1) {
100 return 0;
101 }
102 if (dotPoint > strrchr(realPath, '/')) {
103 int len = dotPoint - realPath;
104 strncpy(path, realPath, len);
105 path[len] = 0;
106 strncat(path + len, suffix, PATH_MAX - len - 1);
107 } else {
108 snprintf(path, PATH_MAX - 1, "%s%s", realPath, suffix);
109 }
110 vf = VFileOpen(path, mode);
111 } else {
112 snprintf(path, PATH_MAX - 1, "%s%s", prefix, suffix);
113 vf = dir->openFile(dir, path, mode);
114 }
115 return vf;
116}