• 12
• 27
• 9
• 20
• 33

# Writing to a file

This topic is 4450 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have a character array of unknown size, created like this:
char* Buffer = new char[variable size];


This buffer gets filled with characters, but I am having trouble writing it out to a file. I know this seems like an easy thing, but it is not outputting correctly. I am using fprintf(). I even tried writing it out character by character (using %c), and making A LOT of calls to fprintf(), it sort of worked, but left spaces in between every character. Does it have to be copied to a char*? If it does, I am kind of having problems doing so. If anyone could help, that would be appreciated. Thank you, Dev578

##### Share on other sites
Well, for C++, you can use std::fstream.write instead. However the C function you should probably use in this case is fwrite if the length is known. For NULL-terminated strings use fputs, and for putting single characters use (f)putc. Only if you actually need to format the output do you need fprintf. I don't know why you get spaces using %c though.

##### Share on other sites
I'm guessing you want to be writing to the file in text mode, and thus 'buffer' is NULL-terminated:

#include <fstream>void Test{	char* buffer = new char[256];	// Do stuff with buffer and NULL-terminate it	// Open a text file	ofstream file("file.txt", ios::out);	// Write the buffer's contents to the file	file << buffer;	file.close();	delete[] buffer;}