Home » Community » Forums » » Simple File I/O Using C++
  Intel sponsors gamedev.net search:   
[Control Panel] [Register] [Bookmarks] [Who's Online] [Active Topics] [Stats] [FAQ] [Search]

Add Forum to Favorites |  Send Topic To a Friend | View Forum FAQ | Track this topic


 Last Thread Next Thread 
 Simple File I/O Using C++
Post Reply 
Nice article, this really is a FAQ on the boards...

You are using a rather old style of C++ though:
1) first, the header file 'iostream' should be used (notice the missing '.h'). These are the new, standard C++ headers, that declare all their stuff in the std namespace and contain some more, minor changes and improvements.

2) second, you are using the old style of casting:
> then you can leaf through a C++ book on pointers if
any 'good' as in up-to-date and correct C++ book will teach you about the static_cast, dynamic_cast, reinterpret_cast and const_cast operators and advise you to prefer these over the old C style of casting.

regards,

BuschnicK


Life would be much easier if I had the source code.
blackfish.sourceforge.net

Edited by - BuschnicK on April 14, 2001 9:50:51 AM

 User Rating: 1015   |  Rate This User  Send Private MessageView Profile Report this Post to a Moderator | Link

quote:
Original post by BuschnicK

Nice article, this really is a FAQ on the boards...

You are using a rather old style of C++ though:
1) first, the header file 'iostream' should be used (notice the missing '.h'). These are the new, standard C++ headers, that declare all their stuff in the std namespace and contain some more, minor changes and improvements.

2) second, you are using the old style of casting:
> then you can leaf through a C++ book on pointers if
any 'good' as in up-to-date and correct C++ book will teach you about the static_cast, dynamic_cast, reinterpret_cast and const_cast operators and advise you to prefer these over the old C style of casting.

regards,

BuschnicK



One little correction, the new C++ standard for file I/O is fstream not iostream. iostream is the old C++ standard.




"And that's the bottom line cause I said so!"

Cyberdrek
Headhunter Soft
A division of DLC Multimedia

Resist Windows XP's Invasive Product Activation Technology!

 User Rating: 1015   |  Rate This User  Send Private MessageView Profile Report this Post to a Moderator | Link

Hi, I just read your file i/o tutorial/article. I must say that it was really good and well written etc. However there is one thing I'm wondering about. And that is how I can make use of the "..." thing using your methods. For example I right now have this code for making a log:

FILE *mpErrorLog;
------------------------------
CFileIO::CFileIO()
{
if(!(mpErrorLog = fopen("log.txt", "w")))
{
perror("Can't init Logfile!\n" );
exit(1);
}

Log("|*|-- Log Init: %s --|*|\n\n", "3D Pong!");

return;
}
----------------------------------
void CFileIO::Log(char *text, ...)
{
va_list Arg;


va_start(Arg,text);

if(mpErrorLog)
{
vfprintf(mpErrorLog, text, Arg);
fflush(mpErrorLog);
}

va_end(Arg);

return;
}

And my question is how should I go on about making a similar log function, using "..." with streams? Is it even doable?

CUselessStuff::NiftyQuote();

 User Rating: 1050   |  Rate This User  Send Private MessageView Profile Report this Post to a Moderator | Link

quote:
Original post by Cyberdrek
One little correction, the new C++ standard for file I/O is fstream not iostream. iostream is the old C++ standard.

A correction of your correction: fstream is the new file I/O library, correct, but iostream is the new general I/O library. The old libraries were declared in fstream.h and iostream.h respectively.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! | Asking Smart Questions ]
Thanks to Kylotan for the idea!


 User Rating: 2027   |  Rate This User  Send Private MessageView ProfileView Journal Report this Post to a Moderator | Link

quote:
Original post by BauerGL
For example I right now have this code for making a log:
<SNIP>!

Frankly, your log code is evil. The reason you're running into problems is because you're simply using C++ as a better C. it's much more than that:
class CLogFile
{
public:
  CLogFile();
  CLogFile( const std::string & filename );
  bool Open( const std::string & filename );
  void Close();

  template <typename T>
  friend std::ostream & operator << ( std::ostream & os, T data );

private:
  bool good;
  std::ofstream fout;
};
.
CLogFile::CLogFile( const std::string & filename )
{
  good = true;
  fout.open( filename.c_str(), ios_base::out|ios_base::app );
  if( fout.fail() )
  {
    // uncomment the next line to print the error to STDERR:
    // std::cerr << "Failed to open log file " << filename << std::endl;
    good = false;
  }
}
.
void CLogFile::Close()
{
  if( fout.is_open() )
    fout.close();
}
.
template <typename T>
std::ostream & operator << ( std::ostream & os, T data )
{
  os << data;
  return os;
}
 

Read up on fstream and iostream, operator overloading and OOP in general.

For the record, I've never really found log classes to be much use. I write quick log routines/loops inside functions that need them.

[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! | Asking Smart Questions ]
Thanks to Kylotan for the idea!


 User Rating: 2027   |  Rate This User  Send Private MessageView ProfileView Journal Report this Post to a Moderator | Link

I know this is a stupid question, but lets say I open a text file in ASCII mode with the ios::at flag activated. How do I choose where I write to the file?

 User Rating: 1015    Report this Post to a Moderator | Link

I know how to write a whole structure to a file, but how do i write a class object to a file(using binary). Is there any simpler way than writing each member of the class one at a time.

 User Rating: 1015    Report this Post to a Moderator | Link

your article talks about reading one text line in a file,how about reading more than one line for example with space caracters from a file

 User Rating: 1015   |  Rate This User  Send Private MessageView Profile Report this Post to a Moderator | Link

Thanx 2 whoever took the time 2 write this article. I have been searching the internet on ways to do this forever!

 User Rating: 1015    Report this Post to a Moderator | Link

Do you guys know of the best way to switch between binary and ASCII streams when performing file I/O?

for example, if you want to write an ASCII header with binary data. Would you just call open a second time in binary mode? It seems like their might be a faster way because calling open will stall the CPU being a system call and all...

Thanks,
Scott

 User Rating: 1015   |  Rate This User  Send Private MessageView Profile Report this Post to a Moderator | Link

Oluseyi
From your source
I got a complie error like this.
I use VC6.0

..\LogFile.cpp(49) : error C2678: binary '<<' : no operator defined which takes a left-hand operand of type 'class CLogFile' (or there is no acceptable conversion)

how can i overcome this?
plz let me know~

 User Rating: 1015   |  Rate This User  Send Private MessageView Profile Report this Post to a Moderator | Link

it doesn't work because the "<<" operator isn't overloaded. You have to manually add a friend function, like this:
friend ostream &operator << (ostream& Buffer, const CLogFile aLog);

But like he said, this class is overkill for a simple log file. If you want the same functionality, use this:
ofstream g_DebugText;

template<class T> inline void SetError(T String)
{
	g_DebugText << String << endl;
}

with this, all you have to do is initialize g_DebugText in the beginning of the program, and shut it down at the end.

 User Rating: 1015   |  Rate This User  Send Private MessageView Profile Report this Post to a Moderator | Link

Ok. Great article. the peek() method gets you the next character without moving the reading position in the file. Is there a getline() equivalent? (like peekline() or something)

 User Rating: 1015   |  Rate This User  Send Private MessageView Profile Report this Post to a Moderator | Link

ok i have one question...how do you write to a file that already as stuff in it and not overwrite that stuff. I am writing a program that stores usernames and passwords in a file, in the program you can add new usernames and passwords to the file but everytime i try that all the old ones get erased.

 User Rating: 1015    Report this Post to a Moderator | Link

generaltak, open the files and have a look for yourself!!

AP, check out the section titled "Opening Files".

appending a file just adds to the end of it,without overwriting.

You want something like this;

ofstream fout("file.duh", ios::app);

If you want to replace a username or password, seek the position, and write to the file normally.

I'm not too sure if the file pointer increments before you add a char, or after, so if it's before, you'll need to move the pointer one char back from the start of your struct(I would use structs for simple text strings, because I come from a C background, you might do things differently)

OK, my turn to ask a question, the author refers to the ios:: as flags, can we use more than one (say, ios::binary and ios::app to append a binary file) together? what is the grammar for this?

 User Rating: 1040   |  Rate This User  Send Private MessageView Profile Report this Post to a Moderator | Link

try it like this:

ofstream fout("File.dat", ios::binary|ios::app);

 User Rating: 1015    Report this Post to a Moderator | Link

how do you create a file for reading or writing without manually typing it in the code

fstream myfile("xxxx.xxx");

For instance, I want the user to supply the filename during program execution.



 User Rating: 1015   |  Rate This User  Send Private MessageView Profile Report this Post to a Moderator | Link

Quote:
Original post by chyke
how do you create a file for reading or writing without manually typing it in the code

fstream myfile("xxxx.xxx");

For instance, I want the user to supply the filename during program execution.


Easy

#include <string>
#include <fstream>

int main()
{
    std::string filename = getSomeInput();
    std::ifstream file( filename.c_str() );
    // use the file
}




 User Rating: 1920   |  Rate This User  Send Private MessageView Profile Report this Post to a Moderator | Link

Thanks rip-0ff



 User Rating: 1015   |  Rate This User  Send Private MessageView Profile Report this Post to a Moderator | Link

How do You create a new directory for a file?

 User Rating: 1015    Report this Post to a Moderator | Link

All times are ET (US)

Post Reply
 Last Thread Next Thread 
Forum Rules:
You may not post new threads
You may post replies
You may not edit your posts
You may not use HTML in your posts
Jump To:
Administrative Options: