How can I know how many bytes does it weight the name of a filename? Just the file, not the full path. I've tried this:
echo 'filename.extension' | wc -c
is this right?
How can I know how many bytes does it weight the name of a filename? Just the file, not the full path. I've tried this:
echo 'filename.extension' | wc -c
is this right?
Looks fine; echo will however add a trailing newline by default, so echo -n or printf are your friend. If you want to convert /path/to/files/like/this/filename.extension to filename.extension, you'd have something like
filepath='/path/to/files/like/this/filename.extension'
namelength=$(printf "%s" "$(basename "${filepath}")" | wc -c)
If you want character (or something similar) length, Not byte count:
There's a much easier way in POSIX-compatible shells (like bash and zsh, so you're probably using one!):
filename="${filepath##*/}"
namelength=${#filename}
The ${#varname} expansion directly gives you the length of the variable.
You're not testing a file name, just a string, but what about this, a quick and dirty hack...
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char **argv) {
int fcount = 1;
int ret = 0;
struct stat fstat_details;
while (fcount != argc) {
ret = stat (argv[fcount], &fstat_details);
if (ret == 0) {
printf ("file: %s, length: %lu\n", argv[fcount], strlen(argv[fcount]));
} else {
printf ("file %s not found\n", argv[fcount]);
}
fcount++;
}
return(0);
}