Jump to content
  • Advertisement
Sign in to follow this  
dev578

Writing to a file

This topic is 4717 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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!