Mohamed Ahmed Nabil
Mohamed Ahmed Nabil

Reputation: 4089

C++: Does the Null get stored when storing a char array in a textfile?

Have a look at this code

ofstream obj("output.txt");
obj<<"Hello World";

Here i send to the text file "output.txt" The char array "Hello World"

Now char arrays are have a terminating null at the end of them.

So when i send the char array to the text file "output.txt", Does the terminating null get sent and stored as well or not and why?

Upvotes: 1

Views: 139

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409356

Consider what would happen if you wrote several times to the file:

ofstream output("myfile.txt");
output << "Hello";
output << " ";
output << "world";

If the string terminator was added each time you write something to the file, when you write the second time the system would then have to find the zero in the file, remove it, and then add it again after the new text. Also, the system would have to be implemented differently for output to e.g. the console.

So to answer your question: No, the terminator is not written. It's only used by strings in memory for functions to know where the strings end in memory.

Upvotes: 6

David
David

Reputation: 1419

No. The null termination is just what C/C++ uses to know where the string ends.

Note that it would be a pretty annoying loss of control to have it write a 0x00 byte after the characters you really want. Then, to just write the characters you want would be a bit of a hassle.

Upvotes: 2

Related Questions