Thursday, July 9, 2009

C++ - How do i read/write text file in C++ programming??

Hi,





I was wondering if any programmers can help me out.





I am currently a student who is required to do a small project.


and one of the requirements is to read/write text file using C++ programming.








so, was wondering if anyone can help me out here....








is it possible for me to read in the text file and store every word in a array?








Like if my text file contains ::





John 14 Student


Peter 26 Engineer


Tom 20 Teacher








and i want to store them in the program like::





name[0]=john


age[0]=14


job[0]=Student





name[1]=Peter


age[1]=26


job[1]=Engineer





name[2]=Tom


age[2]=20


job[2]=Teacher








and to write them back into the text file...





haha is it possible??





hope someone can help ^^





thanks





-Oleo

C++ - How do i read/write text file in C++ programming??
Yes, its very possible. First you need to #include %26lt;fstream%26gt;


then declare an input and output file object like this





ifstream = inputFile; //input file


ofstream = outputFile; //output file





//declare the path of the file to be read


inputFile.open("%26lt;complete path to file%26gt;"); //path c:\text.txt


outputFile.open("%26lt;complete path to file%26gt;");





//then to read from the input file





inputFile %26gt;%26gt; //any variable can be put here, the inputFile %26gt;%26gt; works just like the cin %26gt;%26gt;





//then you can write back to the output file the same way





outputFile %26lt;%26lt; //whatever you want to output, it works just like cout %26lt;%26lt;





//of course this is just pseudo code but you could easily make it work with arrays by adding a for loop. for easier debugging, write the program first with all cin %26gt;%26gt; and cout %26lt;%26lt; statements. once it works that way, replace all the cin %26gt;%26gt; with intputFile %26gt;%26gt; and cout %26lt;%26lt; with outputFile %26lt;%26lt;





//one last thing make sure to close both files when you are done with them





inputFile.close();


outputFile.close();





//its just that simple! happy coding.
Reply:Surely, you can use C++ streams: operators '%26gt;%26gt;' and '%26lt;%26lt;' to write to and read from the file.


Though i write in C++ for a long time, for file input/output i still prefer good old plain C read/write and fscanf/fprintf. You can use any of these two pairs with the same result.

flower girl dresses

No comments:

Post a Comment