Re: Reading data from files
On Apr 9, 10:51 am, "Jeff" <zwj...@gmail.com> wrote:
I have another question. just now, I had read Ilia Yordanov's article
<All About: File I/O in C++>. (download from :http://www.cpp-home.com/
FileIO_tutorial.doc)
In his article,there're code:
#include <fstream>
using namespace std;
int main()
{
ofstream SaveFile("cpp-home.txt");
SaveFile << "Hello World, fromwww.cpp-home.comand Loobian!";
SaveFile.close();
return 0;
}
he said:"This program will create the file cpp-home.txt in the
directory from where you are executing it, and will put "Hello World,
fromwww.cpp-home.comand Loobian!" into it."
It might do that. If the user has autorization to create files
and write to the current directory. Not checking the results of
the open (in the constructor) is something no professional
programmer would do, however. It might, too, if the disk isn't
full, and there are no hardware errors. Not checking the
results of the close is something no professional programmer
would do, however.
why we could not open it as this: inFile.open("people.dat"); ???
Because you can't open an ofstream which is already open.
I generally prefer the separate open as well, because IMHO, it
makes it clearer what the following test is testing, but it's
really a question of style and personal taste, and in a code
review, I wouldn't even both with a comment if someone used the
implicit open in the constructor (unless, of course, the local
coding guidelines had a rule explicitly forbidding it).
I change it to "inFile.open("d:\\test\\people.dat");",only in this way
it can be right.
I'm not sure what context you're talking about. In the example
above, the code creates a file named "cpp-home.txt" in the local
directory, and writes to it. If he's lucky, and no error
occurs, of course.
In your example, you open a file using an absolute pathname, and
guessing from the name of your variable, you want to read it.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34