HaikuDepot: notify work status from main window
[haiku.git] / src / apps / haikudepot / util / StorageUtils.cpp
blob020004577fbf0b9f496b93eef9ca26b4c368aec0
1 /*
2 * Copyright 2017, Andrew Lindesay <apl@lindesay.co.nz>.
3 * All rights reserved. Distributed under the terms of the MIT License.
4 */
6 #include "StorageUtils.h"
8 #include <stdio.h>
9 #include <errno.h>
11 #include <Directory.h>
12 #include <File.h>
13 #include <Entry.h>
14 #include <String.h>
16 #include "Logger.h"
18 #define FILE_TO_STRING_BUFFER_LEN 64
21 /* This method will append the contents of the file at the supplied path to the
22 * string provided.
25 status_t
26 StorageUtils::AppendToString(BPath& path, BString& result)
28 BFile file(path.Path(), O_RDONLY);
29 uint8_t buffer[FILE_TO_STRING_BUFFER_LEN];
30 size_t buffer_read;
32 while((buffer_read = file.Read(buffer, FILE_TO_STRING_BUFFER_LEN)) > 0)
33 result.Append((char *) buffer, buffer_read);
35 return (status_t) buffer_read;
39 /* This method will traverse the directory structure and will remove all of the
40 * files that are present in the directories as well as the directories
41 * themselves.
44 status_t
45 StorageUtils::RemoveDirectoryContents(BPath& path)
47 BDirectory directory(path.Path());
48 BEntry directoryEntry;
49 status_t result = B_OK;
51 while (result == B_OK &&
52 directory.GetNextEntry(&directoryEntry) != B_ENTRY_NOT_FOUND) {
54 bool exists = false;
55 bool isDirectory = false;
56 BPath directoryEntryPath;
58 result = directoryEntry.GetPath(&directoryEntryPath);
60 if (result == B_OK) {
61 result = ExistsObject(directoryEntryPath, &exists, &isDirectory,
62 NULL);
65 if (result == B_OK) {
66 if (isDirectory)
67 RemoveDirectoryContents(directoryEntryPath);
69 if (remove(directoryEntryPath.Path()) == 0) {
70 if (Logger::IsDebugEnabled()) {
71 fprintf(stdout, "did delete [%s]\n",
72 directoryEntryPath.Path());
74 } else {
75 fprintf(stderr, "unable to delete [%s]\n",
76 directoryEntryPath.Path());
77 result = B_ERROR;
83 return result;
87 /* This method checks to see if a file object exists at the path specified. If
88 * something does exist then the value of the 'exists' pointer is set to true.
89 * If the object is a directory then this value is also set to true.
92 status_t
93 StorageUtils::ExistsObject(BPath& path,
94 bool* exists,
95 bool* isDirectory,
96 off_t* size)
98 struct stat s;
100 if (exists != NULL)
101 *exists = false;
103 if (isDirectory != NULL)
104 *isDirectory = false;
106 if (size != NULL)
107 *size = 0;
109 if (-1 == stat(path.Path(), &s)) {
110 if (ENOENT != errno)
111 return B_ERROR;
112 } else {
113 if (exists != NULL)
114 *exists = true;
116 if (isDirectory != NULL)
117 *isDirectory = S_ISDIR(s.st_mode);
119 if (size != NULL)
120 *size = s.st_size;
123 return B_OK;