1. Computing & Technology

Discuss in my forum

What is a Text File?

By , About.com Guide

Manipulating files in C++

C++ uses C functions from cstdio for working with files such as renaming, deleting etc. Text files tend to be used more for logging, configuration etc where file manipulation such as renaming or deleting files is more likely. Binary files are more likely to be data files and generally you won't be deleting and renaming them quite as much as text files.

The two functions you need are

  1. int remove( const char * filename ) ;
  2. int rename( const char * old, const char *new );

Both functions return 0 for success. Also these two function can be used with temporary files.

  1. char * tmpnam( char * str );
  2. FILE * tmpfile( void );

The first returns a random filename, while the second actually creates a randomly named file. I prefer the first as it gives more control. Example 6 (not shown) creates 500 files then removes them. It uses tmpnam, remove, and rename to show these in use. In the first loop it creates 500 randomly named files, writes somethjing in each one then closes it and renames it to a standard name. In the second loop, it deletes all the files based on the standard names. This example uses C++ strings and convert them from C++ to C using the .c_str() method.

The tmpnam function can work in two ways. One is you supply a buffer large enough to hold the name. This is passed in as the parameter str. If you pass in 0 (NULL) then it manages it's own buffer and returns a pointer to it. That's why filename is not malloced while new filename is.

The first printf shows the value of the TMP_MAX constant. This is a system dependent value which shows how many random names can be created before the system starts reusing them or fails. On my XP box the value with Visual C++ is 32767.

Note there is also a newer function

  1. char * tempnam( char * dir, char * prefix);

Where you can specify the directory and prefix of the temporary name.

On the next page: Reading a Config File

©2012 About.com. All rights reserved.

A part of The New York Times Company.