Strike Force Heroes 2
The explosive sequel to the hit game Strike Force Heroes!
3.95 / 5.00 9,661 ViewsObsolescence
Defeat the enormous mechanical beasts--and become one of them.
4.02 / 5.00 44,849 ViewsC++ Main: Booooyyyyyy!
C++ File Input/Output.
----------------------
By: Cyrax88 / Jcrypt [ jcrypt@gmail.com ]
--------------------------------
##########################################
#
File I/O in C++ is as simple as ( cin & cout ) if you can do basic input
and basic output then File I/O shall be a sinch with a little bit of practise.. We'll start with the header that's needed if your reading this i'd recommend you have down the basics of C++ at least... Otherwise this will seem like a bunch of gibberish.. Now the header that will be used for this tutorial will be <fstream> this holds all the predefined functions etc.. we will be using so you basic layout shall look as the following..
##########################################
#
#include <fstream>
using namespace std;
int main{
/*Stuff we'll learn about later*/
return 0;
}
##########################################
#
Now, with this said we can go onto learning about the actual I/O part. Now it's as simple as..
##########################################
#
ofstream fileName("fileToCreate.txt");
/* This will basically work as your output.. Like writing too etc... */
And finally for the input....
ifstream fileName("fileToRead.txt");
/* This will serve as a file "reader" persay so that writing to an existing file will be a breeze */
##########################################
#
Now to go on form what we've learned we are going to vreate a file named "theTut" and we will write "Hello World" to it!...
Each piece i will try to comment as good as possible so sorry for the spacing on the coding this is designed to learn from...
##########################################
#
#include <iostream>
/* Header we use for cin and cout */
#include <fstream>
/* Header we need for File I/O */
using namespace std;
/* This i will go int-depth on in another tutorial */
int main(){
/* Call the basic 'starting point' for the program' */
ofstream myFile("theTut.txt");
/* Remember we are gonna be creating this */
if(myFile.is_open()){
/* Make sure it was opened else give us a error! */
myFile << "Hello, World!\n";
/* Used myFile for the text to be printed to in place of the ( cout ) function. */
myFile.close();
/* Closes the file for us */
cin.get();
/* Basically keeps window open until the enter key is pressed. */
return 0;
/* Make sure the program ends fine. */
}
/* Close the if( )statement */
}
/* Closing bracket we are done! */
##########################################
#
/* Code when formatted correctly */
#include <fstream>
#include <iostream>
using namespace std;
int main(){
ofstream myFile("theTut.txt");
if(myFile.is_open()){
myFile << "Hello, World!\n";
myFile.close();
cin.get();
return 0;
}
}
######################################
Simple, eh!? Now to tackle another aspect of FILE I/O.... input with variables....
######################################
#include <iostream>
#include <fstream>
using namespace std;
int main(){
char myName[] = "Jcrypt";
int age = 17;
ofstream myFile("theTut.txt");
if(myFile.is_open()){
myFile << "My Name: " << myName;
myFile << "\nMy Age: " << age;
myFile.close();
}
cin.get();
return 0;
}
######################################
In the past example, I set basic variables myName, and age. And as mentioned earlier I wrote the values to the file as I would a standard output. To show you exactlly what I meant look how similar these are.
######################################
cout << "My age: " << age << endl;
and...
myFile << "My age: " << age << "\n";
######################################
More to come... in part#2 (sorry outta time at the moment....)
I was wondering why you were going fstream instead of iostream when I first looked at it. Nice! I didn't realize you were going to go into opening outside files for input an output. Nice tute Cy.
Quick question, because I don't know .bat files too well, how would you go about creating a .bat that would hold all the elements of say a <list> or <vector> and read and write to that?
Perpetually looking for time to return to the arts.
or you could just pipe the input/output directly which would pretty much me the same thing (only you wouldn't have other input/output and it would have been simpler)
Actually Cy, I think I'm going to use this as reference tomorrow when I add file I/o portion of code to my C++ final that's due sunday.
Perpetually looking for time to return to the arts.
Yay, heh well hey i'm thinking of finishing this one up actually.... Not sure what else I could add on besides maybe just reading in frm a file? Which isn't much morre typing but yeah.... I will when I have the time in the next couple of days glad to see it helped someone.
You should have added that the header for output is ofstream.h and input is ifstream.h, but fstream.h includes them both..
At 2/21/06 05:46 PM, Inglor wrote: or you could just pipe the input/output directly which would pretty much me the same thing (only you wouldn't have other input/output and it would have been simpler)
Huh?
Sup, bitches :)
how do you add to the end of the file?
not just replace the current text?
woud you have to loading in the previous text then add that and the new text to the file?
ooh and also how do you load variables from a text file?
At 3/16/06 03:05 AM, shazwoogle wrote: how do you add to the end of the file?
not just replace the current text?
woud you have to loading in the previous text then add that and the new text to the file?
ooh and also how do you load variables from a text file?
shag, you can use (eof) to determine end of file and write after that.
Perpetually looking for time to return to the arts.
At 3/16/06 06:20 AM, Johnny_Krysys wrote: shag, you can use (eof) to determine end of file and write after that.
lol shag... eof hey.. ok then thanks ill have a play later with that :D
yeah it would be somewhat like....
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ofstream myFile("tester.txt", ios::app);
if(!myFile.eof()){
cout << "Error: Couldn't Append To End Of File" << endl;
}else{
myFile << "Yay! I can append!" << endl;
}
cin.get();
return 0;
}
And as for making it count lines till the end of file... I'd personally read from the file and take it in as a array of characters..... Then make it increment ++ till it gets to the last character..... Sorry if you still have troubles i'll write more when i get home headin to work so didn't have time for a full code .... cya gl !
At 3/17/06 09:16 AM, Cyrax88 wrote:
:code and such
Another thing that you can do is this. Its a runaround, sort off... but I like the logic of it.
Every time you add something to the file, say a name or phone number... add 1 to a global variable.
When you write to your file, write that number to the top of it. You can that use that number to manipulate stuff, like tell you how many items there are in total.
Then, when you read your file, you can have it read that number first so it says something like..
"Loaded 12 files" or whatever. I used it and it worked well. I'm sure there are easier ways.
Perpetually looking for time to return to the arts.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
using std::cout;
using std::cin;
using std::endl;
using std::string;
int main(){
ofstream dataFile("data.txt");
bool loop = true;
string data;
while (loop == true){
cin>>data;
if (data == "exit"){
exit(1);
}
if(dataFile.eof()){
cout << "Error, cant write to file" << endl;
}else{
dataFile << data<<endl;
}
}
}
that is my code for a test appliction i have made, it works but not to what i want....
the string "data" cant have any spaces in it =(... and i want it to have spaces.. how do i go about this?
Research
cin.get()
and
cin.getline()
One of them might hold the key.
Perpetually looking for time to return to the arts.
is there a manual or anything any where? like the flash help where it has a list of every function?
or even a list with all the basic functions...
At 3/22/06 07:19 PM, Cyrax88 wrote: yes...
http://msdn.microsoft.com
awsome thanks :D
So is there a way of checking if a file is empty or not? say for example, you have a diary program and you wanted to let them chose wether to look at there last diary entry of to write a new one. Because if you have them the option to check the last entry and there wasnt an entry to look at, youd be in a bit of a pickle...
Yeah say if you wanted them to see if there file is empty or not do......
ifstream dia("myDiary.txt");
if(dia.is_open()){
if(sizeof(dia) <= 0){ //Untested but should see if the file is or less than 0 in size.
// Open file or such...
}else{
// error file empty!
}
}
how would I do if I wanted to open a file and read its contents and put it into a variable?
At 3/19/07 08:28 PM, ImpotentBoy2 wrote: i dont get was is_open() does.
is_open() says whether the file opens properly or not.
This bit confused me a bit:
ofstream myFile("theTut.txt");
is that the same as going:
ofstream myFile = "theTut.txt";
Plz explain.
thx.
Bla
I's suppose quite frankly never seen it done the way you supplied. Especially if you were trying to pass attributes along with it... Such ass append etc... example.
std::ofstream file("Some-File.txt", std::ios::app);
std:: - Basically used as a namespace instead of usaing the 'using namespace std' before the call to main.
ios::app - telling our output to append to the end of the file instead of truncate(overwrite) previous data.
I see I never supplied a commented evrsion of reading in a text file to console so here ya go.
#include <fstream>
#include <iostream>
#include <string>
int main(void){
std::ifstream file("Some-File.txt", std::ios::in); //Define which file to read and fill a variable with it.
std::string buffer;
if(file.is_open()){ //Make sure the file opened correctly.
while(!file.eof()){ // Loop until we've reached the end of the file.
getline(file, buffer); //Copy the file into the (string) buffer.
std::cout << buffer << std::endl; // Output the file line by line.
}
}else{
std::cout << "Error: File Could Not Open!!" << std::endl; //Error if file fails to open.
}
std::cin.ignore().get(); // Waits for input ( ENTER ) to be pressed so output is readable.
return 0;
}
Sorry if the format is horribl tried formatting it correctly for readability sake. ~James
I just don't understand what "myFile" does in this:
ofstream myFile("theTut.txt");
It looks like a method call, but the name isn't that of any existing method call.
Also, "ofstream" looks like a type declaration... It's really confusing.
Why is there a space between ofstream and myFile, is "myFile" an argument passed to "ofstream?" if so, does that mean that ofstream(myFile("theTut.txt")) would work as well?
Thx.
Bla
At 3/20/07 08:37 PM, Alphabit wrote: I just don't understand what "myFile" does in this:
ofstream myFile("theTut.txt");
Thx.
When you say
ofstream myFile( "theTut.txt" );
It's just a quick way of saying
ofstream myFile;
myFile.open( "theTut.txt" );
What you're doing is opening the file in the declaration of the stream reader, for readability and convenience.
At 3/20/07 08:52 PM, RageOfOrder wrote: When you say
ofstream myFile( "theTut.txt" );
It's just a quick way of saying
ofstream myFile;
myFile.open( "theTut.txt" );
What you're doing is opening the file in the declaration of the stream reader, for readability and convenience.
Oh ok, thx I think I get it now. So if I was to convert this to Java, it would look something like this?
ofstream myFile = new ofstream("theTut.txt")
Isn't there a "new" keyword in C++? Are classes initialized as soon as they're declared?
Bla
At 3/20/07 09:18 PM, Alphabit wrote: Oh ok, thx I think I get it now. So if I was to convert this to Java, it would look something like this?
ofstream myFile = new ofstream("theTut.txt")
Yea.
Isn't there a "new" keyword in C++? Are classes initialized as soon as they're declared?
Yes, there is, but it's beyond the scope of, and not needed for this tutorial.