Dominic Mason
Dominic Mason

Reputation: 307

Can I store NULL in a string?

I want to perform some lengthy operations on a large file, which will involve lots and lots of seeking. (The current version of the program takes 5 hours and uses fseek at least 15,057,456 times.) As a result, I am hoping to load the file into the ram, and use char* instead of FILE*. Can I load null characters from the file into the char* array if I:

  1. Malloc the char array, and store its length separately, and
  2. Only use character operations on the array (i.e. newchar = *(pointertothearray+offset) ), avoiding operations like strcpy or strstr?

Upvotes: 0

Views: 180

Answers (2)

Man Vs Code
Man Vs Code

Reputation: 1057

You can load the entire file's contents into memory. Essentially this buffer will be a byte stream and not a string.

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 148870

You can load the whole file in a dynamic char array (malloc'ed on the heap) even if there are null characters in it : a null character is a valid char.

But you cannot call it a string. A C string is from specification of language a null terminated char array.

So as long as you only use offsets, mem... functions and no str... functions, there is no problems having null characters in a char array.

Upvotes: 6

Related Questions