00:00
00:00
Newgrounds Background Image Theme

Matilly just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

C++: File I/o

14,091 Views | 28 Replies
New Topic Respond to this Topic

C++: File I/o 2006-02-21 17:34:55


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

Response to C++: File I/o 2006-02-21 17:42:55


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?


Writer @ www.Johnrickett.com

Response to C++: File I/o 2006-02-21 17:46:09


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)

Response to C++: File I/o 2006-03-03 02:58:47


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.


Writer @ www.Johnrickett.com

Response to C++: File I/o 2006-03-03 09:15:49


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.

Response to C++: File I/o 2006-03-03 12:11:39


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

Response to C++: File I/o 2006-03-16 03:05:47


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?

Response to C++: File I/o 2006-03-16 06:20:58


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.


Writer @ www.Johnrickett.com

Response to C++: File I/o 2006-03-17 01:13:57


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

Response to C++: File I/o 2006-03-17 09:16:17


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 !

Response to C++: File I/o 2006-03-17 19:25:08


cool thanks =D

Response to C++: File I/o 2006-03-17 21:02:44


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.


Writer @ www.Johnrickett.com

Response to C++: File I/o 2006-03-19 00:51:36



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

Response to C++: File I/o 2006-03-19 02:19:56


Research

cin.get()

and

cin.getline()

One of them might hold the key.


Writer @ www.Johnrickett.com

Response to C++: File I/o 2006-03-20 02:31:13


ok i will thanks

Response to C++: File I/o 2006-03-22 18:57:00


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

Response to C++: File I/o 2006-03-22 19:19:27


Response to C++: File I/o 2006-03-23 02:39:09


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

awsome thanks :D

Response to C++: File I/o 2006-06-04 08:43:24


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

Response to C++: File I/o 2006-06-05 14:49:45


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

Response to C++: File I/o 2006-11-30 15:50:06


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

Response to C++: File I/o 2007-03-19 20:28:39


i dont get was is_open() does.

Response to C++: File I/o 2007-03-19 21:47:03


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.

Response to C++: File I/o 2007-03-20 03:11:48


This bit confused me a bit:

ofstream myFile("theTut.txt");

is that the same as going:

ofstream myFile = "theTut.txt";

Plz explain.
thx.


Bla

Response to C++: File I/o 2007-03-20 15:53:11


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.

Response to C++: File I/o 2007-03-20 16:00:43


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

Response to C++: File I/o 2007-03-20 20:37:06


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

Response to C++: File I/o 2007-03-20 21:18:56


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

Response to C++: File I/o 2007-06-05 09:14:46


At 3/19/06 02:19 AM, Johnny wrote: Research

cin.get()

and

cin.getline()

One of them might hold the key.

it's

getline(cin,varname)

or something like that.


Hello.