Reputation: 23
How do you write multiple lines to a file? ... This is what I have.. Also, some of the lines include text like: #import <Foundation/Foundation.h>
How would I go about doing this? The code below is what I have right now..
//Creates Config.h
FILE * pFile;
char *buffer = "//Empty Header File";
char file [256];
sprintf (file , "%s/Desktop/%s/Control.h",homeDir, game_name);
pFile = fopen (file, "w+");
fwrite (buffer , sizeof(char), sizeof(buffer), pFile);
fclose (pFile);
Upvotes: 0
Views: 4147
Reputation: 96845
Since this is C++, I suggest you utilize the standard IOStreams library and use the concrete file stream classes std::ifstream
and std::ofstream
for handling files. They implement RAII to handle the closing of the file, and use built in operators and the read()
/write()
member functions to perform formatted and unformatted I/O respectively. Moreover, they blend well together with the use of std::basic_string
, the standard C++ string class.
With that said, if we implement this in C++ correctly, it should look like this:
std::string path = "/Desktop/";
std::string filename = homeDir + path + game_name + "/Control.h";
std::ofstream file(filename, std::ios_base::app);
This handles opening the file, but as you say you wish to write multiple lines to a file. Well this is simple. Just use '\n'
whenever you wish to put a newline:
file << buffer << '\n';
If you give us more information about your issue, I will be able to elaborate more in my answer. But until you do, the above is sufficient.
Upvotes: 1
Reputation: 99172
In C++ you would do it like this:
ofstream fout("someplace/Control.h");
fout << "a line of text" << endl;
fout << "another line of text" << endl;
I've left out some details like how to construct a filename and how to open a file in "append" mode, but you should try to tackle one problem at a time.
Upvotes: 0
Reputation: 17053
Change to
sprintf (file , "%s/Desktop/%s/Control.h\n",homeDir, game_name);
\n - is a new-line code.
Upvotes: 0