Say I have to remove the last occurrence of a string from another string. How would I go about it?
To elaborate, I have a file name in ac string (gchar* or char* )
C:\\SomeDir\\SomeFolder\\MyFile.pdf
and I want to remove the extension .pdf , and change it to something else, eg .txt or .png . What is the least troublesome yet efficient , convenient and cross-platform way to do it? Thanks.
note : I know this is an extremely simple thing to do in C++ but for this project , I absolutely MUST use C and no other language. (academic requirement)
note 2 : Although you can suggest other third-party library , I currently only have access to the C standard library and the GLib.
note 3 : I have searched for similar questions with the "C" tag, but can't seem to find any.
have a look at basename.
NAME
dirname, basename - Parse pathname components
SYNOPSIS
#include <libgen.h>
char *dirname(char *path);
char *basename(char *path);
DESCRIPTION
Warning: there are two different functions basename() - see below.
The functions dirname() and basename() break a null-terminated
pathname string into directory and filename components. In the
usual case, dirname() returns the string up to, but not including,
the final ’/’, and basename() returns the component following the
final ’/’. Trailing ’/’ characters are not counted as part of the
pathname.
I would normally use the "splitpath" function to seperate all four parts of a full path name (dir, path, name, ext). Best regards Oliver
char fil[] = "C:\\SomeDir\\SomeFolder\\MyFile.pdf";
char fil2[1000];
char extension[] = ".tmp";
// search for . and add new extension
sprintf(fil2, "%s%s", strtok(fil, "."), extension);
printf("%s\n", fil2);
Just modifying the above 'strtok' code with 'strrchr' function
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_PATH 255
int main()
{
char f[MAX_PATH] = "dir\\file.pdf";
char f1[MAX_PATH];
char ext[] = ".tmp";
char *ptr = NULL;
// find the last occurance of '.' to replace
ptr = strrchr(f, '.');
// continue to change only if there is a match found
if (ptr != NULL) {
snprintf(f1, (ptr-f)+1, "%s", f);
strcat(f1, ext);
}
printf("%s\n", f1);
return 1;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.