Important alert: (current site time 7/15/2013 6:35:52 PM EDT)
 

VB icon

C++ File I/O Examples

Email
Submitted on: 12/5/2000 11:04:50 AM
By: *LuckY* 
Level: Beginner
User Rating: By 14 Users
Compatibility: C++ (general)
Views: 76874
(About the author)
 
     This demonstrates an example of C++'s fstream File I/O. Very simple; the basic stuff for beginners to learn from. If you would like to see how to do something more in the direction this code leads, comment on (and rate) it telling me what specifically you want to see and I'll be glad to suffice.
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
//**************************************
// Name: C++ File I/O Examples
// Description:This demonstrates an example of C++'s fstream File I/O. Very simple; the basic stuff for beginners to learn from. If you would like to see how to do something more in the direction this code leads, comment on (and rate) it telling me what specifically you want to see and I'll be glad to suffice.
// By: *LuckY*
//
//This code is copyrighted and has// limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=930&lngWId=3//for details.//**************************************

//
// lucky760@yahoo.com
//
#include <fstream>
const char *FILENAME = "FILE.txt";
int main() {
	//create output object associated w/ file
	ofstream fout(FILENAME);
	cout << "Enter your secret password: ";
	char str[60];
	cin >> str;
	//write to file
	fout << "This is your secret password. Don't give it to anyone!\n";
	fout << str;
	//close file
	fout.close();
	cout << endl;
	ifstream fin(FILENAME);
	char ch;
	while (fin.get(ch))
		cout << ch;
	fin.close();	
	return 0;
}


Other 23 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Beginner category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

12/6/2000 10:12:13 PMDvad78

Nice code, Could you show a little more file input?
(If this comment was disrespectful, please report it.)

 
12/8/2000 11:14:17 PMPhilip Neil

Hey *Lucky* I am a newbie C++ but I have a rough idea about whats going on here. const char *FILENAME =
(If this comment was disrespectful, please report it.)

 
12/8/2000 11:19:25 PMphilip neil

ok lets try that again.. In do this and edit the const to the path but it doesn't write to the file. Can u help me man
(If this comment was disrespectful, please report it.)

 
12/24/2000 6:55:26 PMDennis Wrenn

Hello Jim, I think what you want is the seekp member of the ofstream class
you find the position of a space, however you are doing that, then you do:
fstream f("example.txt", ios::in | ios::out);
//do find stuff...
f.seekp(pos);
f << ",";
f.close()


simple :-)
(If this comment was disrespectful, please report it.)

 
1/21/2001 4:34:00 PMLiam

hey you forgot to include iostream.h
but other wise it's cool, i don't suppose you could help me, i've been trying to create a program that will let you enter a file name for the input
thanx Ü
(If this comment was disrespectful, please report it.)

 
1/23/2001 5:32:45 PM*LuckY*

Most newer compilers, Liam, don't require you to include if is already included. That's the reason for its absence.

To enter your own name for a file do something like this:

char str[20];
cout << "Enter filename: ";
cin.getline(str,20);
ofstream f(str);

hth
(If this comment was disrespectful, please report it.)

 
1/24/2001 4:05:23 PMTom

Hey man... good code, I think I understand it well enough to utilize it. I was wondering, though, how might I output the values of variables to a file, then, later on, read those values back into the variables? Example: I have two int variables, first and second. first = 32 and second = 12. I want to output these two variables to the same file, then be able to read them back in (say, if I changed the values and wanted to change them back to whatever their value in the file was).
(If this comment was disrespectful, please report it.)

 
1/24/2001 4:41:57 PM*LuckY*

Tom:

do something like the following:
//do file stuff first of course
int x=32,y=12;
fout << x << endl; //don't forget the endl
fout << y << endl;
int a,b;
fin >> a;
fin >> b;

(If this comment was disrespectful, please report it.)

 
3/28/2001 8:16:48 PMIce man

Sorry about that above. I don't know what went wrong. Anyways, if someone could explain WHY or HOW the fstream works, I would greatly apreciate it. I understand how to use it, but I don't understand how it works
(If this comment was disrespectful, please report it.)

 
4/11/2001 3:35:48 PMJason

I want to read a file using fstream, but my input file is , delimited not space delimited. How should I read each field in my file with >>? Thanks
(If this comment was disrespectful, please report it.)

 
4/22/2001 5:43:01 PMbar

Hi. I am working on a school project, and I have to keep some data in binary files (names and phone numbers of customers, descriptions of classes in a gym, etc). Is there any way you could explain the major difference between I/O of normal text files and I/O of binary files? This is like a sink or swim project and I am kind of lost...I have only worked with .txt files so far. Thank you.
(If this comment was disrespectful, please report it.)

 
4/26/2001 11:27:48 PMCharlie

I'd like to write a program that displays 10 lines of output from a file and then pauses untill the user strikes a key to show the next 10 lines of code, (etc. etc.) until the it reaches the eof? Can you help me?
Thanks Charlie
(If this comment was disrespectful, please report it.)

 
5/10/2001 8:12:53 AMtoasthouse

I like this beginning code. I'm new to C and am trying to learn how to grab a string variable from a dat file and then create another dat file with the extracted string variable from the first dat file. Any suggestions?
(If this comment was disrespectful, please report it.)

 
5/10/2001 8:20:00 AMmom

I am new to C++ and I am trying to write a program that will open a dat file(containing name and id on one line), read the id and then write the name to a new dat file. I've gotten the program to read the file but I can't figure out how to close the read.dat file , move the name info to a new dat file and display it or print it. Can you offer any suggestions to help me?
(If this comment was disrespectful, please report it.)

 
6/20/2001 8:59:01 AMscrump

ok i understand how to use fstream.h. but last night i made the switch to linux only, windows98 installed and wouldnt boot! lol but, the ios modes included in the borland package and vc++ pack, have alot more options. such as if file doesnt exist dont create, append, trunc and so on. But the gnu compiler, g++'s fstream only allows in and out, and no file checking. has any one heard of header that i could use that would better suit my needs.
(If this comment was disrespectful, please report it.)

 
7/24/2001 12:54:52 AMBipin Patel

Can you help me with me program. This what I want to do. I am writing a program in Visual C . This is all about I/O file. I want to search into directory in any drive for string. The string will be inserted by user on dialog editbox 4 to 5 strings (ie.
(If this comment was disrespectful, please report it.)

 
7/24/2001 1:24:11 AMBipin Patel

continue....(ie. "ACY","00:17:26","sa") Something like this. After the string is found it should display only those line that contain found string. because later on I will have to put that lines block in Access Data base. If you can't help me with all this please atleast help me with reading more than one file at time for string.
(If this comment was disrespectful, please report it.)

 
8/10/2001 9:48:45 AMHomer

Hi
I am writing a program for a school which will allow the user to input student details and then append the records to a student file status.dat, it will then read the file and display the contents on screen. I'm using borland turbo c++........can you please give me an example of code that will do this ie create the file and display contents.........cheers.
(If this comment was disrespectful, please report it.)

 
9/23/2001 6:52:51 PMwillow

HI there. I need to read a series of chars from a file I done know how many chars are on each line. Some may have 3 others four my problem is I also have ints in this file that I want to read. How do I do this
(If this comment was disrespectful, please report it.)

 
9/23/2001 6:59:42 PMwillow

The above is kinda hard to understand let me give an example. I have in my file, an idnum 123, an amount 3 and a code rts, so my file looks like this. 123 3 RTS. The next line in my file may look like this. 142 4 GLDA and the next, 456 1 P. how do I read from such a file not knowing if the character section has 1, 2, or 3 characters?
I want to read them individualy.
(If this comment was disrespectful, please report it.)

 
2/5/2002 10:26:44 AMzoran

It is not , it is file that you need to include at the top. Apart from that, the code is cool
(If this comment was disrespectful, please report it.)

 
2/5/2002 10:44:42 AM*LuckY*

It depends on your compiler. I compiled with borland. In visual c++ you have to use
(If this comment was disrespectful, please report it.)

 
4/15/2002 9:24:16 PM☻☺KDDFLX☺☻

This all sounds great and all, but unfortunatly for me, i don't use Borland(not that its bad or anything.), I use DJGPP/gcc. It seems that it doesnt have fstream.h. is there a clone of that or something i can use?BTW, this is pretty good
(If this comment was disrespectful, please report it.)

 
4/22/2002 6:34:54 AMquestion

Hi...I'm beginner...I'm doing my assignment about wild card, and it needs to open a file. Do you know how to take information from for example data.txt and put it into an array. So in the data.txt there are information such cat dog fly elephent and after opening the data.txt the array will contain the info array[1]=cat ect...Thank YOuuuuuuu....=p
(If this comment was disrespectful, please report it.)

 
4/23/2002 11:39:26 AMKeith

How would I save and load a double linked list to my program
(If this comment was disrespectful, please report it.)

 
6/20/2002 2:37:21 PMcjr

hey can you email me and tell how all of this works

(If this comment was disrespectful, please report it.)

 
9/26/2002 11:02:04 AM

Hi,
Can anyone email me how to get file timestamp or file prtoperties.
My email: bahruddina@yahoo.com
Thanx in advance for ur help.

(If this comment was disrespectful, please report it.)

 
9/26/2002 11:05:41 AM

Hi%2C%0D%0ACan+anyone+email+me+how+to++get+file+timestamp+or+file+prtoperties%2E%0D%0AMy +email%3A+bahruddina%40yahoo%2Ecom%0D%0AThanx+in+advance+for+ur+help%2E%0D%0A
(If this comment was disrespectful, please report it.)

 
10/9/2002 4:15:15 AM

Am a beginner trying to write a programme which will calculate the Average of nth entered number. I tried the for statment and got stacked. Can someone help me out?

int main()
{ int values=0;
float sum=0, number;

cout << "enter the number of value you want the average";
cin >> values;

for(int j=1; j<=values; j++)
{ cout << "enter number :";
cin >> number;
sum +=number;
}
cout <<"The average is\t"<
get.cin();
retrun 0;
}


I do want the answers in exponential number. Will like it i 2 decemial places
(If this comment was disrespectful, please report it.)

 
10/10/2002 5:31:09 PM

Just to state to those who are
(If this comment was disrespectful, please report it.)

 
10/10/2002 5:35:13 PM

Just to state to those who are "correcting" the beginners or commenting on the example. If you're writing C++, its not and not .
(If this comment was disrespectful, please report it.)

 
11/24/2002 1:03:56 PM

Hello there, can anyone please help me with File I/O using C++.I would like to read from a file more than one variable data type. My file would have a name and scores below is a test line:

Good Jack 40 60 20 30 80 90

how do i enter all this using >>?
please email me: ekseman@yahoo.com

thanx
(If this comment was disrespectful, please report it.)

 
3/4/2003 9:18:54 PM

hey this is all very neat, but can anyone tell me how to read a folder lets say Temp and within it contains unknown filename to the programer and user. Can i make some sort of function or use built in functions to read the folder and it returns the filenames of all the contents inside the folder? including extension and of course it probably would return as a string.
(If this comment was disrespectful, please report it.)

 
3/5/2003 6:49:35 PM*LuckY*

Look up functions called findfirst() and findnext()
(If this comment was disrespectful, please report it.)

 
3/10/2003 7:19:06 AM

hi is there any way i can rename my function with a string that i search from a text file.
Thanks in advance.
enjoyy
(If this comment was disrespectful, please report it.)

 
7/10/2003 1:54:50 AM

Hello there, can anyone please help me
with File I/O using C++.I would like to
read from a file more than one variable
data type. My file would have a name
and scores below is a test
line:

Good Jack 40 60 20 30 80 90
kaks ka 45 45 65 65 65 65

(If this comment was disrespectful, please report it.)

 
12/16/2003 10:54:38 AM

I am using MS C ++ and this code won't work unless you add these lines of code;

using std::ofstream;
using std::ifstream;
#include
using std::cout;
using std::cin;
using std::endl;
(If this comment was disrespectful, please report it.)

 
12/29/2003 10:29:46 PM

Nice code. I need some help in writing a C program to read a text file and write the contents onto another file. Both the file names and the record separator shd be accepted as parameters.
The input file contents could be say :
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa;bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb;The
entire data is organized as a single line without a new line
character in between but each record is separated by a semi-colon. I need to
read upto the first ";" - semi-colon and write this as the first record in
the output file. Again upto the next ";" and write this as the second
record and so on.
There is no restriction on the input and output file size.

Can u plz help me out with this?
(If this comment was disrespectful, please report it.)

 
12/30/2003 10:02:50 AM*LuckY*

1) For future programming questions try a message board (such as http://cboard.cprogramming.com)
2) Look up class "string" and the global function "getline" and its arguments.
(If this comment was disrespectful, please report it.)

 
12/27/2004 8:09:44 PMDavid Westfall

This is awesome but I was wondering
if you could email me at:
littlegames@mail.com and tell
me how to write general c++ code
that will show the output of
a text file line by line. and make
it able to read a certain line
in the middle of the file.

thanks.
(If this comment was disrespectful, please report it.)

 
7/17/2006 4:54:32 PMPaul Boehm

Its generous of you to share this code. For a begginner like myself many people don't want to jot down simple code like this even if it saves someone hours of time. I wanted to know if you could demostrate how to perform a simple math operation (i.e. cosine) on the contents of a files raw binary contents. I've been trying for years and can't figure it out. If not, I still appreciate your time in helping others out.

Sincerly,
Paul Boehm
(If this comment was disrespectful, please report it.)

 
2/3/2007 5:36:01 PMRafa A.M. Preto

Thank's for the example: simple and efficient, like all things should be;)
(If this comment was disrespectful, please report it.)

 
11/11/2009 8:48:34 PMJohn

Hi,

I'm trying to read integers from a text file and place them into an array. The text file looks something like this:

80 81
82
83 84 85
86 87

etc

Any idea how to do this? I know that I'll need a for loop, but how to I read 1 integer at a time?

Thanks!
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.