Be a Supporter!
Jcrypt
Jcrypt
  • Member since: Aug. 23, 2005
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
C++: File I/o Feb. 21st, 2006 @ 05:34 PM Reply

C++ 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....)

Johnny
Johnny
  • Member since: Apr. 17, 2004
  • Offline.
Forum Stats
Member
Level 24
Blank Slate
Response to C++: File I/o Feb. 21st, 2006 @ 05:42 PM Reply

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.

BBS Signature
Inglor
Inglor
  • Member since: Jan. 26, 2003
  • Offline.
Forum Stats
Member
Level 17
Blank Slate
Response to C++: File I/o Feb. 21st, 2006 @ 05:46 PM Reply

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)

Johnny
Johnny
  • Member since: Apr. 17, 2004
  • Offline.
Forum Stats
Member
Level 24
Blank Slate
Response to C++: File I/o Mar. 3rd, 2006 @ 02:58 AM Reply

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.

BBS Signature
Jcrypt
Jcrypt
  • Member since: Aug. 23, 2005
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Mar. 3rd, 2006 @ 09:15 AM Reply

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.

liam
liam
  • Member since: Dec. 11, 2004
  • Offline.
Forum Stats
Member
Level 22
Blank Slate
Response to C++: File I/o Mar. 3rd, 2006 @ 12:11 PM Reply

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 :)

BBS Signature
shazwoogle
shazwoogle
  • Member since: Sep. 27, 2004
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Mar. 16th, 2006 @ 03:05 AM Reply

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?

Johnny
Johnny
  • Member since: Apr. 17, 2004
  • Offline.
Forum Stats
Member
Level 24
Blank Slate
Response to C++: File I/o Mar. 16th, 2006 @ 06:20 AM Reply

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.

BBS Signature
shazwoogle
shazwoogle
  • Member since: Sep. 27, 2004
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Mar. 17th, 2006 @ 01:13 AM Reply

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

Jcrypt
Jcrypt
  • Member since: Aug. 23, 2005
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Mar. 17th, 2006 @ 09:16 AM Reply

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 !

shazwoogle
shazwoogle
  • Member since: Sep. 27, 2004
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Mar. 17th, 2006 @ 07:25 PM Reply

cool thanks =D

Johnny
Johnny
  • Member since: Apr. 17, 2004
  • Offline.
Forum Stats
Member
Level 24
Blank Slate
Response to C++: File I/o Mar. 17th, 2006 @ 09:02 PM Reply

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.

BBS Signature
shazwoogle
shazwoogle
  • Member since: Sep. 27, 2004
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Mar. 19th, 2006 @ 12:51 AM Reply


#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?

Johnny
Johnny
  • Member since: Apr. 17, 2004
  • Offline.
Forum Stats
Member
Level 24
Blank Slate
Response to C++: File I/o Mar. 19th, 2006 @ 02:19 AM Reply

Research

cin.get()

and

cin.getline()

One of them might hold the key.


Perpetually looking for time to return to the arts.

BBS Signature
shazwoogle
shazwoogle
  • Member since: Sep. 27, 2004
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Mar. 20th, 2006 @ 02:31 AM Reply

ok i will thanks

shazwoogle
shazwoogle
  • Member since: Sep. 27, 2004
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Mar. 22nd, 2006 @ 06:57 PM Reply

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...

Jcrypt
Jcrypt
  • Member since: Aug. 23, 2005
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Mar. 22nd, 2006 @ 07:19 PM Reply

yes...
http://msdn.microsoft.com

shazwoogle
shazwoogle
  • Member since: Sep. 27, 2004
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Mar. 23rd, 2006 @ 02:39 AM Reply

At 3/22/06 07:19 PM, Cyrax88 wrote: yes...
http://msdn.microsoft.com

awsome thanks :D

neowolf22964
neowolf22964
  • Member since: May. 1, 2004
  • Offline.
Forum Stats
Member
Level 08
Blank Slate
Response to C++: File I/o Jun. 4th, 2006 @ 08:43 AM Reply

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...

Jcrypt
Jcrypt
  • Member since: Aug. 23, 2005
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Jun. 5th, 2006 @ 02:49 PM Reply

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!
}
}

phyconinja
phyconinja
  • Member since: Sep. 18, 2004
  • Offline.
Forum Stats
Member
Level 25
Blank Slate
Response to C++: File I/o Nov. 30th, 2006 @ 03:50 PM Reply

how would I do if I wanted to open a file and read its contents and put it into a variable?

GeoKureli
GeoKureli
  • Member since: Apr. 1, 2003
  • Offline.
Forum Stats
Supporter
Level 19
Game Developer
Response to C++: File I/o Mar. 19th, 2007 @ 08:28 PM Reply

i dont get was is_open() does.

CaptinChu
CaptinChu
  • Member since: Sep. 11, 2005
  • Offline.
Forum Stats
Member
Level 15
Blank Slate
Response to C++: File I/o Mar. 19th, 2007 @ 09:47 PM Reply

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.

Alphabit
Alphabit
  • Member since: Feb. 14, 2006
  • Offline.
Forum Stats
Member
Level 09
Blank Slate
Response to C++: File I/o Mar. 20th, 2007 @ 03:11 AM Reply

This bit confused me a bit:

ofstream myFile("theTut.txt");

is that the same as going:

ofstream myFile = "theTut.txt";

Plz explain.
thx.


Bla

Jcrypt
Jcrypt
  • Member since: Aug. 23, 2005
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Mar. 20th, 2007 @ 03:53 PM Reply

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.

Jcrypt
Jcrypt
  • Member since: Aug. 23, 2005
  • Offline.
Forum Stats
Member
Level 11
Blank Slate
Response to C++: File I/o Mar. 20th, 2007 @ 04:00 PM Reply

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

Alphabit
Alphabit
  • Member since: Feb. 14, 2006
  • Offline.
Forum Stats
Member
Level 09
Blank Slate
Response to C++: File I/o Mar. 20th, 2007 @ 08:37 PM Reply

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

RageOfOrder
RageOfOrder
  • Member since: Aug. 30, 2002
  • Offline.
Forum Stats
Member
Level 09
Blank Slate
Response to C++: File I/o Mar. 20th, 2007 @ 08:52 PM Reply

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.

Alphabit
Alphabit
  • Member since: Feb. 14, 2006
  • Offline.
Forum Stats
Member
Level 09
Blank Slate
Response to C++: File I/o Mar. 20th, 2007 @ 09:18 PM Reply

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

RageOfOrder
RageOfOrder
  • Member since: Aug. 30, 2002
  • Offline.
Forum Stats
Member
Level 09
Blank Slate
Response to C++: File I/o Mar. 20th, 2007 @ 10:25 PM Reply

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.