ADDED: Some useful functions for Files and Text management

// File management functions
 - int FileRename(const char *fileName, const char *fileRename); // Rename file (if exists)
 - iint FileRemove(const char *fileName);                         // Remove file (if exists)
 - iint FileCopy(const char *srcPath, const char *dstPath);       // Copy file from one path to another, dstPath created if it doesn't exist
 - iint FileMove(const char *srcPath, const char *dstPath);       // Move file from one directory to another, dstPath created if it doesn't exist
 - int FileTextReplace(const char *fileName, const char *search, const char *replacement); // Replace text in an existing file
 - iint FileTextFindIndex(const char *fileName, const char *search); // Find text in existing file

// Text management functions
 - const char *TextRemoveSpaces(const char *text);                                       // Remove text spaces, concat words
 - char *GetTextBetween(const char *text, const char *begin, const char *end);           // Get text between two strings
 - char *TextReplace(const char *text, const char *search, const char *replacement);     // Replace text string (WARNING: memory must be freed!)
 - char *TextReplaceBetween(const char *text, const char *begin, const char *end, const char *replacement); // Replace text between two specific strings (WARNING: memory must be freed!)
This commit is contained in:
Ray
2025-09-18 15:34:09 +02:00
parent bd6065a4fd
commit c264c86ee0
3 changed files with 278 additions and 78 deletions

View File

@@ -1127,10 +1127,17 @@ RLAPI bool SaveFileText(const char *fileName, const char *text); // Save text d
//------------------------------------------------------------------
// File system functions
RLAPI int FileRename(const char *fileName, const char *fileRename); // Rename file (if exists)
RLAPI int FileRemove(const char *fileName); // Remove file (if exists)
RLAPI int FileCopy(const char *srcPath, const char *dstPath); // Copy file from one path to another, dstPath created if it doesn't exist
RLAPI int FileMove(const char *srcPath, const char *dstPath); // Move file from one directory to another, dstPath created if it doesn't exist
RLAPI int FileTextReplace(const char *fileName, const char *search, const char *replacement); // Replace text in an existing file
RLAPI int FileTextFindIndex(const char *fileName, const char *search); // Find text in existing file
RLAPI bool FileExists(const char *fileName); // Check if file exists
RLAPI bool DirectoryExists(const char *dirPath); // Check if a directory path exists
RLAPI bool IsFileExtension(const char *fileName, const char *ext); // Check file extension (recommended include point: .png, .wav)
RLAPI int GetFileLength(const char *fileName); // Get file length in bytes (NOTE: GetFileSize() conflicts with windows.h)
RLAPI long GetFileModTime(const char *fileName); // Get file modification time (last write time)
RLAPI const char *GetFileExtension(const char *fileName); // Get pointer to extension for a filename string (includes dot: '.png')
RLAPI const char *GetFileName(const char *filePath); // Get pointer to filename for a path string
RLAPI const char *GetFileNameWithoutExt(const char *filePath); // Get filename string without extension (uses static string)
@@ -1148,7 +1155,6 @@ RLAPI void UnloadDirectoryFiles(FilePathList files); // Unload file
RLAPI bool IsFileDropped(void); // Check if a file has been dropped into window
RLAPI FilePathList LoadDroppedFiles(void); // Load dropped filepaths
RLAPI void UnloadDroppedFiles(FilePathList files); // Unload dropped filepaths
RLAPI long GetFileModTime(const char *fileName); // Get file modification time (last write time)
// Compression/Encoding functionality
RLAPI unsigned char *CompressData(const unsigned char *data, int dataSize, int *compDataSize); // Compress data (DEFLATE algorithm), memory must be MemFree()
@@ -1504,7 +1510,7 @@ RLAPI int GetCodepointPrevious(const char *text, int *codepointSize);
RLAPI const char *CodepointToUTF8(int codepoint, int *utf8Size); // Encode one codepoint into UTF-8 byte array (array length returned as parameter)
// Text strings management functions (no UTF-8 strings, only byte chars)
// WARNING 1: Most of these functions use internal static buffers, it's recommended to store returned data on user-side for re-use
// WARNING 1: Most of these functions use internal static buffers[], it's recommended to store returned data on user-side for re-use
// WARNING 2: Some strings allocate memory internally for the returned strings, those strings must be free by user using MemFree()
RLAPI char **LoadTextLines(const char *text, int *count); // Load text as separate lines ('\n')
RLAPI void UnloadTextLines(char **text, int lineCount); // Unload text lines
@@ -1513,12 +1519,15 @@ RLAPI bool TextIsEqual(const char *text1, const char *text2);
RLAPI unsigned int TextLength(const char *text); // Get text length, checks for '\0' ending
RLAPI const char *TextFormat(const char *text, ...); // Text formatting with variables (sprintf() style)
RLAPI const char *TextSubtext(const char *text, int position, int length); // Get a piece of a text string
RLAPI char *TextReplace(const char *text, const char *replace, const char *by); // Replace text string (WARNING: memory must be freed!)
RLAPI const char *TextRemoveSpaces(const char *text); // Remove text spaces, concat words
RLAPI char *GetTextBetween(const char *text, const char *begin, const char *end); // Get text between two strings
RLAPI char *TextReplace(const char *text, const char *search, const char *replacement); // Replace text string (WARNING: memory must be freed!)
RLAPI char *TextReplaceBetween(const char *text, const char *begin, const char *end, const char *replacement); // Replace text between two specific strings (WARNING: memory must be freed!)
RLAPI char *TextInsert(const char *text, const char *insert, int position); // Insert text in a position (WARNING: memory must be freed!)
RLAPI char *TextJoin(char **textList, int count, const char *delimiter); // Join text strings with delimiter
RLAPI char **TextSplit(const char *text, char delimiter, int *count); // Split text into multiple strings, using MAX_TEXTSPLIT_COUNT static strings
RLAPI void TextAppend(char *text, const char *append, int *position); // Append text at specific position and move cursor!
RLAPI int TextFindIndex(const char *text, const char *find); // Find first text occurrence within a string, -1 if not found
RLAPI void TextAppend(char *text, const char *append, int *position); // Append text at specific position and move cursor
RLAPI int TextFindIndex(const char *text, const char *search); // Find first text occurrence within a string, -1 if not found
RLAPI char *TextToUpper(const char *text); // Get upper case version of provided string
RLAPI char *TextToLower(const char *text); // Get lower case version of provided string
RLAPI char *TextToPascal(const char *text); // Get Pascal case notation version of provided string

View File

@@ -1927,6 +1927,115 @@ void SetConfigFlags(unsigned int flags)
// Module Functions Definition: File system
//----------------------------------------------------------------------------------
// Rename file (if exists)
// NOTE: Only rename file name required, not full path
int FileRename(const char *fileName, const char *fileRename)
{
int result = 0;
if (FileExists(fileName))
{
result = rename(fileName, fileRename);
}
else result = -1;
return result;
}
// Remove file (if exists)
int FileRemove(const char *fileName)
{
int result = 0;
if (FileExists(fileName))
{
result = remove(fileName);
}
else result = -1;
return result;
}
// Copy file from one path to another
// NOTE: If destination path does not exist, it is created!
int FileCopy(const char *srcPath, const char *dstPath)
{
int result = 0;
int srcDataSize = 0;
unsigned char *srcFileData = LoadFileData(srcPath, &srcDataSize);
// Create required paths if they do not exist
if (!DirectoryExists(GetDirectoryPath(dstPath)))
result = MakeDirectory(GetDirectoryPath(dstPath));
if (result == 0) // Directory created successfully (or already exists)
{
if ((srcFileData != NULL) && (srcDataSize > 0))
result = SaveFileData(dstPath, srcFileData, srcDataSize);
}
UnloadFileData(srcFileData);
return result;
}
// Move file from one directory to another
// NOTE: If dst directories do not exists they are created
int FileMove(const char *srcPath, const char *dstPath)
{
int result = 0;
if (FileExists(srcPath))
{
FileCopy(srcPath, dstPath);
FileRemove(srcPath);
}
else result = -1;
return result;
}
// Replace text in an existing file
// WARNING: DEPENDENCY: [rtext] module
int FileTextReplace(const char *fileName, const char *search, const char *replacement)
{
int result = 0;
char *fileText = NULL;
char *fileTextUpdated = { 0 };
#if defined(SUPPORT_MODULE_RTEXT)
if (FileExists(fileName))
{
fileText = LoadFileText(fileName);
fileTextUpdated = TextReplace(fileText, search, replacement);
result = SaveFileText(fileName, fileTextUpdated);
MemFree(fileTextUpdated);
UnloadFileText(fileText);
}
#else
TRACELOG(LOG_WARNING, "FILE: File text replace requires [rtext] module");
#endif
return result;
}
// Find text index position in existing file
// WARNING: DEPENDENCY: [rtext] module
int FileTextFindIndex(const char *fileName, const char *search)
{
int result = -1;
if (FileExists(fileName))
{
char *fileText = LoadFileText(fileName);
char *ptr = strstr(fileText, search);
if (ptr != NULL) result = (int)(ptr - fileText);
UnloadFileText(fileText);
}
return result;
}
// Check if the file exists
bool FileExists(const char *fileName)
{
@@ -2054,6 +2163,21 @@ int GetFileLength(const char *fileName)
return size;
}
// Get file modification time (last write time)
long GetFileModTime(const char *fileName)
{
struct stat result = { 0 };
long modTime = 0;
if (stat(fileName, &result) == 0)
{
time_t mod = result.st_mtime;
modTime = (long)mod;
}
return modTime;
}
// Get pointer to extension for a filename string (includes the dot: .png)
// WARNING: We just get the ptr but not the extension as a separate string
const char *GetFileExtension(const char *fileName)
@@ -2367,7 +2491,7 @@ void UnloadDirectoryFiles(FilePathList files)
// Create directories (including full path requested), returns 0 on success
int MakeDirectory(const char *dirPath)
{
if ((dirPath == NULL) || (dirPath[0] == '\0')) return 1; // Path is not valid
if ((dirPath == NULL) || (dirPath[0] == '\0')) return -1; // Path is not valid
if (DirectoryExists(dirPath)) return 0; // Path already exists (is valid)
// Copy path string to avoid modifying original
@@ -2392,9 +2516,12 @@ int MakeDirectory(const char *dirPath)
// Create final directory
if (!DirectoryExists(pathcpy)) MKDIR(pathcpy);
RL_FREE(pathcpy);
// In case something failed and requested directory
// was not successfully created, return -1
if (!DirectoryExists(dirPath)) return -1;
return 0;
}
@@ -2513,22 +2640,6 @@ void UnloadDroppedFiles(FilePathList files)
}
}
// Get file modification time (last write time)
long GetFileModTime(const char *fileName)
{
struct stat result = { 0 };
long modTime = 0;
if (stat(fileName, &result) == 0)
{
time_t mod = result.st_mtime;
modTime = (long)mod;
}
return modTime;
}
//----------------------------------------------------------------------------------
// Module Functions Definition: Compression and Encoding
//----------------------------------------------------------------------------------
@@ -2903,7 +3014,7 @@ unsigned int *ComputeSHA1(unsigned char *data, int dataSize)
for (int offset = 0; offset < newDataSize; offset += (512/8))
{
// Break chunk into sixteen 32-bit words w[j], 0 <= j <= 15
unsigned int w[80] = {0};
unsigned int w[80] = { 0 };
for (int i = 0; i < 16; i++)
{
w[i] = (msg[offset + (i*4) + 0] << 24) |

View File

@@ -1649,34 +1649,79 @@ const char *TextSubtext(const char *text, int position, int length)
return buffer;
}
// Remove text spaces, concat words
const char *TextRemoveSpaces(const char *text)
{
static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
if (text != NULL)
{
// Avoid copying the ' ' characters
for (int i = 0, j = 0; (i < MAX_TEXT_BUFFER_LENGTH - 1) && (text[j] != '\0'); i++)
{
if (text[i] != ' ') { buffer[j] = text[i]; j++; }
}
}
return buffer;
}
// Get text between two strings
static char *GetTextBetween(const char *text, const char *begin, const char *end)
{
#define MAX_TEXT_BETWEEN_SIZE 1024
static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
int beginIndex = TextFindIndex(text, begin);
if (beginIndex > -1)
{
int beginLen = strlen(begin);
int endIndex = TextFindIndex(text + beginIndex + beginLen, end);
if (endIndex > -1)
{
endIndex += (beginIndex + beginLen);
int len = (endIndex - beginIndex - beginLen);
if (len < (MAX_TEXT_BETWEEN_SIZE - 1)) strncpy(buffer, text + beginIndex + beginLen, len);
else strncpy(buffer, text + beginIndex + beginLen, MAX_TEXT_BETWEEN_SIZE - 1);
}
}
return buffer;
}
// Replace text string
// REQUIRES: strstr(), strncpy(), strcpy()
// TODO: If (replacement == NULL) remove "search" text
// WARNING: Allocated memory must be manually freed
char *TextReplace(const char *text, const char *replace, const char *by)
char *TextReplace(const char *text, const char *search, const char *replacement)
{
// Sanity checks and initialization
if (!text || !replace || !by) return NULL;
char *result = NULL;
if (!text || !search) return NULL; // Sanity check
char *insertPoint = NULL; // Next insert point
char *temp = NULL; // Temp pointer
int replaceLen = 0; // Replace string length of (the string to remove)
int byLen = 0; // Replacement length (the string to replace by)
int lastReplacePos = 0; // Distance between replace and end of last replace
int searchLen = 0; // Search string length of (the string to remove)
int replaceLen = 0; // Replacement length (the string to replace by)
int lastReplacePos = 0; // Distance between next search and end of last replace
int count = 0; // Number of replacements
replaceLen = TextLength(replace);
if (replaceLen == 0) return NULL; // Empty replace causes infinite loop during count
searchLen = TextLength(search);
if (searchLen == 0) return NULL; // Empty search causes infinite loop during count
byLen = TextLength(by);
replaceLen = TextLength(replacement);
// Count the number of replacements needed
insertPoint = (char *)text;
for (count = 0; (temp = strstr(insertPoint, replace)); count++) insertPoint = temp + replaceLen;
for (count = 0; (temp = strstr(insertPoint, search)); count++) insertPoint = temp + searchLen;
// Allocate returning string and point temp to it
temp = result = (char *)RL_MALLOC(TextLength(text) + (byLen - replaceLen)*count + 1);
temp = result = (char *)RL_MALLOC(TextLength(text) + (replaceLen - searchLen)*count + 1);
if (!result) return NULL; // Memory could not be allocated
@@ -1686,11 +1731,11 @@ char *TextReplace(const char *text, const char *replace, const char *by)
// - 'text' points to the remainder of text after "end of replace"
while (count--)
{
insertPoint = strstr(text, replace);
insertPoint = strstr(text, search);
lastReplacePos = (int)(insertPoint - text);
temp = strncpy(temp, text, lastReplacePos) + lastReplacePos;
temp = strcpy(temp, by) + byLen;
text += lastReplacePos + replaceLen; // Move to next "end of replace"
temp = strcpy(temp, replacement) + replaceLen;
text += lastReplacePos + searchLen; // Move to next "end of replace"
}
// Copy remaind text part after replacement to result (pointed by moving temp)
@@ -1699,6 +1744,41 @@ char *TextReplace(const char *text, const char *replace, const char *by)
return result;
}
// Replace text between two specific strings
// REQUIRES: strlen(), strncpy()
// NOTE: If (replacement == NULL) remove "begin"[ ]"end" text
// WARNING: Returned string must be freed by user
char *TextReplaceBetween(const char *text, const char *begin, const char *end, const char *replacement)
{
char *result = NULL;
if (!text || !begin || !end) return NULL; // Sanity check
int beginIndex = TextFindIndex(text, begin);
if (beginIndex > -1)
{
int beginLen = strlen(begin);
int endIndex = TextFindIndex(text + beginIndex + beginLen, end);
if (endIndex > -1)
{
endIndex += (beginIndex + beginLen);
int textLen = strlen(text);
int replaceLen = (replacement == NULL)? 0 : strlen(replacement);
int toreplaceLen = endIndex - beginIndex - beginLen;
result = (char *)RL_CALLOC(textLen + replaceLen - toreplaceLen + 1, sizeof(char));
strncpy(result, text, beginIndex + beginLen); // Copy first text part
if (replacement != NULL) strncpy(result + beginIndex + beginLen, replacement, replaceLen); // Copy replacement (if provided)
strncpy(result + beginIndex + beginLen + replaceLen, text + endIndex, textLen - endIndex); // Copy end text part
}
}
return result;
}
// Insert text in a specific position, moves all text forward
// WARNING: Allocated memory must be manually freed
char *TextInsert(const char *text, const char *insert, int position)
@@ -1761,11 +1841,11 @@ char **TextSplit(const char *text, char delimiter, int *count)
// 1. Maximum number of possible split strings is set by MAX_TEXTSPLIT_COUNT
// 2. Maximum size of text to split is MAX_TEXT_BUFFER_LENGTH
static char *result[MAX_TEXTSPLIT_COUNT] = { NULL };
static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
static char *buffers[MAX_TEXTSPLIT_COUNT] = { NULL }; // Pointers to buffer[] text data
static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 }; // Text data with '\0' separators
memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
result[0] = buffer;
buffers[0] = buffer;
int counter = 0;
if (text != NULL)
@@ -1780,7 +1860,7 @@ char **TextSplit(const char *text, char delimiter, int *count)
else if (buffer[i] == delimiter)
{
buffer[i] = '\0'; // Set an end of string at this point
result[counter] = buffer + i + 1;
buffers[counter] = buffer + i + 1;
counter++;
if (counter == MAX_TEXTSPLIT_COUNT) break;
@@ -1789,7 +1869,7 @@ char **TextSplit(const char *text, char delimiter, int *count)
}
*count = counter;
return result;
return buffers;
}
// Append text at specific position and move cursor
@@ -1803,11 +1883,11 @@ void TextAppend(char *text, const char *append, int *position)
// Find first text occurrence within a string
// REQUIRES: strstr()
int TextFindIndex(const char *text, const char *find)
int TextFindIndex(const char *text, const char *search)
{
int position = -1;
char *ptr = strstr(text, find);
char *ptr = strstr(text, search);
if (ptr != NULL) position = (int)(ptr - text);
@@ -1885,7 +1965,7 @@ char *TextToPascal(const char *text)
// WARNING: Limited functionality, only basic characters set
char *TextToSnake(const char *text)
{
static char buffer[MAX_TEXT_BUFFER_LENGTH] = {0};
static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
if (text != NULL)
@@ -1913,7 +1993,7 @@ char *TextToSnake(const char *text)
// WARNING: Limited functionality, only basic characters set
char *TextToCamel(const char *text)
{
static char buffer[MAX_TEXT_BUFFER_LENGTH] = {0};
static char buffer[MAX_TEXT_BUFFER_LENGTH] = { 0 };
memset(buffer, 0, MAX_TEXT_BUFFER_LENGTH);
if (text != NULL)