1 /* 2 * Copyright 2017, Andrew Lindesay <apl@lindesay.co.nz>. 3 * All rights reserved. Distributed under the terms of the MIT License. 4 */ 5 6 #include "StorageUtils.h" 7 8 #include <stdio.h> 9 #include <errno.h> 10 11 #include <Directory.h> 12 #include <File.h> 13 #include <Entry.h> 14 #include <String.h> 15 16 #include "Logger.h" 17 18 #define FILE_TO_STRING_BUFFER_LEN 64 19 20 21 /* This method will append the contents of the file at the supplied path to the 22 * string provided. 23 */ 24 25 status_t 26 StorageUtils::AppendToString(BPath& path, BString& result) 27 { 28 BFile file(path.Path(), O_RDONLY); 29 uint8_t buffer[FILE_TO_STRING_BUFFER_LEN]; 30 size_t buffer_read; 31 32 while((buffer_read = file.Read(buffer, FILE_TO_STRING_BUFFER_LEN)) > 0) 33 result.Append((char *) buffer, buffer_read); 34 35 return (status_t) buffer_read; 36 } 37 38 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. 42 */ 43 44 status_t 45 StorageUtils::RemoveDirectoryContents(BPath& path) 46 { 47 BDirectory directory(path.Path()); 48 BEntry directoryEntry; 49 status_t result = B_OK; 50 51 while (result == B_OK && 52 directory.GetNextEntry(&directoryEntry) != B_ENTRY_NOT_FOUND) { 53 54 bool exists = false; 55 bool isDirectory = false; 56 BPath directoryEntryPath; 57 58 result = directoryEntry.GetPath(&directoryEntryPath); 59 60 if (result == B_OK) { 61 result = ExistsObject(directoryEntryPath, &exists, &isDirectory, 62 NULL); 63 } 64 65 if (result == B_OK) { 66 if (isDirectory) 67 RemoveDirectoryContents(directoryEntryPath); 68 69 if (remove(directoryEntryPath.Path()) == 0) { 70 if (Logger::IsDebugEnabled()) { 71 fprintf(stdout, "did delete [%s]\n", 72 directoryEntryPath.Path()); 73 } 74 } else { 75 fprintf(stderr, "unable to delete [%s]\n", 76 directoryEntryPath.Path()); 77 result = B_ERROR; 78 } 79 } 80 81 } 82 83 return result; 84 } 85 86 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. 90 */ 91 92 status_t 93 StorageUtils::ExistsObject(BPath& path, 94 bool* exists, 95 bool* isDirectory, 96 off_t* size) 97 { 98 struct stat s; 99 100 if (exists != NULL) 101 *exists = false; 102 103 if (isDirectory != NULL) 104 *isDirectory = false; 105 106 if (size != NULL) 107 *size = 0; 108 109 if (-1 == stat(path.Path(), &s)) { 110 if (ENOENT != errno) 111 return B_ERROR; 112 } else { 113 if (exists != NULL) 114 *exists = true; 115 116 if (isDirectory != NULL) 117 *isDirectory = S_ISDIR(s.st_mode); 118 119 if (size != NULL) 120 *size = s.st_size; 121 } 122 123 return B_OK; 124 } 125