C strlen and strcmp
Check the end of a filename when listing receipts saved as PDFs.
A simple example
strlen and strcmp
- Start with "abc" and "bc"
- Do this Compare the ending
- Result Yes
#include <stdio.h>
#include <string.h>
int main(void) {
const char *value = "abc";
const char *other = "bc";
printf("%s\n", (strlen(value) >= strlen(other) && strcmp(value + strlen(value) - strlen(other), other) == 0) ? "yes" : "no");
return 0;
}
yes
Syntax
strlen(label) >= 4 && strcmp(label + strlen(label) - 4, ".pdf") == 0
Run these examples in C
Save one example at a time as lesson.c. Use C17 and a Unix-style shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonFind filenames with a receipt extension
A document picker displays receipt files alongside unrelated attachments. Filter by the expected ending so the clerk sees the right filenames before opening any of the files.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *label = "receipt.pdf";
printf("%s\n", (strlen(label) >= 4 && strcmp(label + strlen(label) - 4, ".pdf") == 0) ? "yes" : "no");
return 0;
}
yes
The final four characters match .pdf. A filename such as receipt.pdf.old would fail the check.
Find a class roster
A folder contains active exports alongside files with similar names and additional suffixes. Inspect the final filename or extension carefully before placing an entry in the report.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *value = "class.csv";
const char *other = ".csv";
printf("%s\n", (strlen(value) >= strlen(other) && strcmp(value + strlen(value) - strlen(other), other) == 0) ? "yes" : "no");
return 0;
}
yes
The final characters match the requested extension.
Exclude a backup export
A registry keeps an earlier export by adding an extra extension to its filename. Test the filename's final suffix before treating the file as part of today's import.
#include <stdio.h>
#include <string.h>
int main(void) {
const char *value = "class.csv.old";
const char *other = ".csv";
printf("%s\n", (strlen(value) >= strlen(other) && strcmp(value + strlen(value) - strlen(other), other) == 0) ? "yes" : "no");
return 0;
}
no
The final extension is .old.
What to watch for
A filename suffix describes a naming convention. It cannot verify the contents of a file.