Jump to content

Extract file extension: Difference between revisions

→‎{{header|C}}: Adjusted code to changed requirements
(→‎{{header|Go}}: Adjusted code to the changed task description)
(→‎{{header|C}}: Adjusted code to changed requirements)
Line 248:
=={{header|C}}==
 
<lang C>#include <assert.h>
{{update|C|The format of a suffix has been clarified, and the test-cases have been replaced with new ones.}}
 
<lang C>
#include <assert.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
 
/* Returns a pointer to the extension of 'string'. If no extension is found,
* thenIf no extension is found, returns a pointer to the null-terminatorend of 'string'. */
char* file_ext(const char *string)
{
Line 267 ⟶ 264:
 
for (char *iter = ext + 1; *iter != '\0'; iter++) {
if (!isalnum((unsigned char)*iter))
return (char*) string + strlen(string);
}
 
return ext + 1;
}
 
int main(void)
{
const char *stringstestcases[][2] = {
{"picturehttp://example.jpgcom/download.tar.gz", ".gz"},
{"http://mywebsiteCharacterModel.con/picture/image3DS", ".png3DS"},
{"myuniquefile.longextensiondesktop", ".desktop"},
{"IAmAFileWithoutExtensiondocument", ""},
{"/path/todocument.my/filetxt_backup", ""},
{"file/etc/pam.odd_oned/login", ""}
};
 
int exitcode = 0;
for (intsize_t i = 0; i < sizeof(stringstestcases) / sizeof(stringstestcases[0]); i++i) {
printf("'%s' - '%s'\n", strings[i], file_ext(strings[i]));
const char *ext = file_ext(testcases[i][0]);
if (strcmp(ext, testcases[i][1]) != 0) {
fprintf(stderr, "expected '%s' for '%s', got '%s'\n",
testcases[i][1], testcases[i][0], ext);
exitcode = 1;
}
}
return exitcode;
}
}</lang>
{{out}}
<pre>
'picture.jpg' - 'jpg'
'http://mywebsite.con/picture/image.png' - 'png'
'myuniquefile.longextension' - 'longextension'
'IAmAFileWithoutExtension' - ''
'/path/to.my/file' - ''
'file.odd_one' - ''
</pre>
 
=={{header|C++}}==
Cookies help us deliver our services. By using our services, you agree to our use of cookies.