Sunday, July 12, 2009

Outputting data from c++ into file?

Hello,





I would like to know how to, in my c++ program, write certain bits of data directly to file instead of writing it to the screen. My program asks me for specific input then after I give the parameters I want it to take the output values that would normally be put to the stream but then instead be directed to a file I create. on top of that I would like to be able to somehow make it so that each time I execute the program it writes the data to consecutive files. For example the first file would be "file1" the second "file2" and so on.





Thanks,





Brian

Outputting data from c++ into file?
Whew! That's daunting! Ok, here it goes.





to start with, create a file called "iterator.txt" and put the letter 'A' into it.





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





main... (all that gibberish that goes in the "main" declaration)


{





//get the letter value of this current time running the program


//this will help in naming the final output file.


ifstream iterator = "iterator.txt"; //open an input file


char iteration = iterator.get(); //get a value out of a file


iterator.close(); //close a file


ofstream nextVal = "iterator.txt"; //open an output file


nextVal.put(iteration + 1); //put a character into a file


nextVal.close(); //close a file





//now to create and write the output file.


ofstream outputFile = "file" + iteration + ".txt"





//write to the output file


*outputFile %26lt;%26lt; "Send some stuff to the file, yo." %26lt;%26lt; endl;





//remember to close your file


outputFile.close();


}








That's the basic gist of it. I'm doing this all from memory, so I'm sure there are bugs in the code. Use a search engine to fill in the gaps in what I've told you here.
Reply:#include %26lt;fstream.h%26gt;


int main()


{


fstream file_op("c:\\file.ext ",ios::out);





file_op%26lt;%26lt;"wirte to file this line ";


file_op.close();


return 0;


}
Reply:*slaps forhead* dude, there are only like 5,000,000 recources at your disposal that tell you how to do this:





http://www.cplusplus.com/doc/tutorial/





don't program unless you want to do a lot of technical reading and abuse search engines
Reply:# include%26lt;iostream.h%26gt;


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


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





int main(void)


{


fstream file_output("C:\\sample.fil"ios::out);





file_out%26lt;%26lt;":-) I have done it!";





file_out.close();





getch();


No comments:

Post a Comment