Sign in to follow this  

Writing to a file

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
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 this post


Link to post
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;
}

Share this post


Link to post
Share on other sites

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

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this