#include <stdio.h>
#include <string.h>
/*
* Removes the last file extension from a path or filename.
*
* Examples:
* "document.pdf" -> "document"
* "archive.tar.gz" -> "archive.tar"
* "photo.jpg" -> "photo"
* "README" -> "README"
* "/tmp/file.txt" -> "/tmp/file"
*
* Parameters:
* filename Input filename or path.
* output Output buffer.
* outputSize Size of output buffer.
*
* Returns:
* 0 on success.
* -1 on error.
*/
int removeFileExtension(
const char *filename,
char *output,
size_t outputSize)
{
const char *dot;
const char *slash1;
const char *slash2;
const char *lastSeparator;
size_t length;
if (filename == NULL || output == NULL || outputSize == 0) {
return -1;
}
/* Copy original string safely. */
strncpy(output, filename, outputSize - 1);
output[outputSize - 1] = '\0';
/* Find the last dot. */
dot = strrchr(output, '.');
/* Find the last path separator. */
slash1 = strrchr(output, '/');
slash2 = strrchr(output, '\\');
lastSeparator = slash1;
if (slash2 != NULL &&
(lastSeparator == NULL || slash2 > lastSeparator))
{
lastSeparator = slash2;
}
/*
* Remove the extension only if the dot belongs
* to the filename and is not part of a directory.
*/
if (dot != NULL &&
(lastSeparator == NULL || dot > lastSeparator))
{
* (char *)dot = '\0';
}
length = strlen(output);
return (length < outputSize) ? 0 : -1;
}
int main(void)
{
const char *filename = "archive.tar.gz";
char result[256] = "";
if (removeFileExtension(filename, result, sizeof(result)) == 0) {
printf("Original: %s\n", filename);
printf("Without extension: %s\n", result);
}
if (removeFileExtension("document.pdf", result, sizeof(result)) == 0) {
printf("Original: %s\n", "document.pdf");
printf("Without extension: %s\n", result);
}
if (removeFileExtension("README", result, sizeof(result)) == 0) {
printf("Original: %s\n", "README");
printf("Without extension: %s\n", result);
}
if (removeFileExtension("/tmp/file.txt", result, sizeof(result)) == 0) {
printf("Original: %s\n", "/tmp/file.txt");
printf("Without extension: %s\n", result);
}
return 0;
}
/*
run:
Original: archive.tar.gz
Without extension: archive.tar
Original: document.pdf
Without extension: document
Original: README
Without extension: README
Original: /tmp/file.txt
Without extension: /tmp/file
*//