Reputation: 257
I am trying to delete .txt extension from filename that is written in string "mat":
sscanf(mat, "%s.txt", ime_datoteke);
If mat="sm04567890.txt"
I want that ime_datoteke="sm04567890"
.
As in example I tried using sscanf
, but it doesnt work (it copies mat to ime_datoteke).
How can I do it in C?
Upvotes: 0
Views: 102
Reputation: 145839
With the Standard C function strstr
:
char a[] ="sm04567890.txt";
char *b = strstr(a, ".txt");
*b = '\0';
printf("%s\n", a);
will print:
sm04567890
Upvotes: 0
Reputation: 9916
This example uses strrchr()
to locate the last period in the string, and then copies only the part of the string that preceeds that period.
If no period is found, the entire string is copied.
const char *fullstop;
if ((fullstop = strrchr(mat, '.')))
strncpy(ime_datoteke, mat, fullstop - mat);
else
strcpy(ime_datoteke, mat);
Upvotes: 1
Reputation: 8928
Use strrchr:
char* pch = strrchr(str,'.');
if(pch)
*pch = '\0';
Upvotes: 1
Reputation: 81349
You could modify your sscanf
approach slightly to read a string that does not include a .
:
sscanf(mat, "%[^.].txt", ime_datoteke);
However, it would be best if you look for the .
character from the end of the string, and then copy the substring determined by it.
char* dot = strrchr(mat, '.');
strncpy(ime_datoteke, mat, dot - mat);
Upvotes: 1