string - How to check if there is a `\0` character in a filename using C? -


i'd write function this:

int validate_file_name(char *filename) {     //... } 

which will:

  • return 1 if there no \0 character in filename,
  • 0 otherwise.

i thought may achieved using simple for(size_t = 0; < strlen(filename); i++), don't know how determine how characters i've got check?

i can't use strlen() because terminate on first occurrence of \0 character.

how should approach problem?


clarification:

i trying apply these guidelines filename receive. if should avoid putting \0 in filename, how validate if you've got no size parameter.

moreover, there strings multiple \0 characters, here: http://www.gnu.org/software/libc/manual/html_mono/libc.html#argz-and-envz-vectors. still, had no idea impossible determine length if not explicitly provided.


conclusion:

there no way can determine length of string not null-terminated. unless know length of course or deploy dirty hacks: checking if pointer allocated memory or not.

you trying solve problem not need solved.

a file name string. in c, "string" definition "a contiguous sequence of characters terminated , including first null character".

it impossible have string or file name null character embedded in it.

it's possible have sequence of characters embedded null character. example:

char buf[] = "foo\0bar.txt"; 

buf array of 12 characters; characters @ positions 3 , 11 both null characters. if treat buf string, example calling

fopen(buf, "r") 

it treated string length of 3 (the length of string not include terminating null character).

if you're working character arrays may or may not contain strings, makes sense you're asking. need keep track of size of buffer separately address of initial character, either passing additional argument or wrapping pointer , length in structure.

but if you're dealing file names, it's best deal strings , assume whatever char* value passed function points valid string. if doesn't (if there no null character anywhere in array), that's caller's fault, , not can reasonably check.

(incidentally, unix/linux file systems explicitly forbid null characters in file names. / character forbidden, because it's used directory name delimiter. windows file systems have stricter rules.)

one last point: null (a macro expands to) null pointer constant. please don't use term null refer null character '\0'.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -