Monday, May 24, 2010

Can you have two or more files open for writing when doing C++ programming?

I'm using this syntax to open the file for writing:


pointertoopenfile = fopen("file.txt","w");





To restate my question, can I open two or more files like this to write to in C++? I would like to open up two or three files at the beginning of my program, be able to write to them throughout the program, and then close them all when I'm done.





It seems like it only works to have 1 file open for writing at a time. My other option is just to open and close each file as I want to write to it and append to previous written text with:





pointertoopenfile = fopen("file.txt","a");

Can you have two or more files open for writing when doing C++ programming?
Absolutely yes!


Full Code(How I do it):


#include %26lt;fstream.h%26gt;


int main ()


{


fstream file1;


fstream file2;


file1.open("file1.txt",ios::out);


file2.open("file2.txt",ios::out);


file1%26lt;%26lt;"Hi!";


file2%26lt;%26lt;"Bye!";


file1.close;


file2.close;


return 1;


}
Reply:I have a program that opens and writes to 4 files:





f1 = fopen(File1, “w”);


f2 = fopen(File2, “w”);


f3 = fopen(File3, “w”);


f4 = fopen(File4, “w”);
Reply:As long as you use a different variable for each file (pointertoopenfile1, pointertoopenfile2, pointertoopenfile3) you won't have any problem.





But, depending on the file type (text, data), you may be able to open the file for append and just add to it. So you can open the file, append, close the file. That way, if the program crashes, or it has to abort, everything it wrote so far is saved.


No comments:

Post a Comment