Library contents

C strlen and strcmp

Check the end of a filename when listing receipts saved as PDFs.

A simple example

strlen and strcmp

  1. Start with "abc" and "bc"
  2. Do this Compare the ending
  3. Result Yes
The final two characters are exactly b and c.
lesson.c
#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;
}
Output
yes

Syntax

C 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
./lesson

Find 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.

From the programconst char *label = "receipt.pdf"
Resultyes
lesson.c
#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;
}
Output
yes

The final four characters match .pdf. A filename such as receipt.pdf.old would fail the check.

Advertisements

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.

From the programconst char *value = "class.csv"
Resultyes
lesson.c
#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;
}
Output
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.

From the programconst char *value = "class.csv.old"
Resultno
lesson.c
#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;
}
Output
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.

Documentation for strlen and strcmp