Home arrow C++ arrow Page 4 - Focusing on C++ Files
C++

Focusing on C++ Files


In this third part of a five-part series on C++, you will learn how to do a variety of things with files. This article is excerpted from chapter 10 of the C++ Cookbook, written by Ryan Stephens, Christopher Diggins, Jonathan Turkanis and Jeff Cogswell (O'Reilly; ISBN: 0596007612). Copyright © 2007 O'Reilly Media, Inc. All rights reserved. Used with permission from the publisher. Available from booksellers or direct from O'Reilly Media.

Author Info:
By: O'Reilly Media
Rating: 3 stars3 stars3 stars3 stars3 stars / 2
October 30, 2008
TABLE OF CONTENTS:
  1. · Focusing on C++ Files
  2. · 10.7 Copying a File
  3. · 10.8 Deleting or Renaming a File
  4. · 10.9 Creating a Temporary Filename and File

print this article
SEARCH DEVARTICLES

TOOLS YOU CAN USE

advertisement
Focusing on C++ Files - 10.9 Creating a Temporary Filename and File
(Page 4 of 4 )

Problem

You have to store some stuff on disk temporarily, and you don't want to have to write a routine that generates a unique name yourself.

Solution

Use either the tmpfile or tmpnam functions, declared in <cstdio>. tmpfile returns a FILE* that is already opened for writing, and tmpnam generates a unique filename that you can open yourself. Example 10-13 shows how to use tmpfile.

Example 10-13. Creating a temporary file

#include <iostream>
#include <cstdio>

int main() {

   FILE* pf = NULL;
  
char buf[256];

   pf = tmpfile(); // Create and open a temp file

   if (pf) {
      fputs("This is a temp file", pf); // Write some data to it
   }

   fseek(pf, 5, SEEK_SET);  // Reset the file position
   fgets(buf, 255, pf);     // Read a string from it
   fclose(pf);

   std::cout << buf << '\n';
}

Discussion

There are two ways to create a temporary file; Example 10-13 shows the first way. The function tmpfile is declared in <cstdio>, takes no parameters, and returns a FILE* if successful, NULL if not. The FILE* is the same type you can use with the C input/output functions fread, fwrite, fgets, fputs, etc. tmpfile opens the temporary file in "wb+" mode, which means you can write to it or read from it in binary mode (i.e., the characters are not interpreted as they are read). When your program terminates normally, the temporary file created by tmpfile is automatically deleted.

This may or may not work for you depending on your requirements. You will notice that tmpfile does not give you a filename--how do you pass the file to another program? You can't; you'll have to use a similar function instead: tmpnam.

tmpnam doesn't actually create a temporary file, it just creates a unique file name that you can use to go open a file using that name yourself. tmpnam takes a single char* parameter and returns a char*. You can pass in a pointer to a char buffer (that has to be at least as big as the macro L_tmpnam, also defined in <cstdio>), where tmpnam will copy the temporary name, and it will return a pointer to the same buffer. If you pass in NULL, tmpfile will return a pointer to a static buffer that contains the filename, which means that subsequent calls to tmpnam will overwrite it. (See Example 10-14.)

Example 10-14. Creating a temporary filename

#include <iostream>
#include <fstream>
#include <cstdio>
#include <string>

int main() {

   char* pFileName = NULL;

   pFileName = tmpnam(NULL);
   // Right here is where another program may get the same temp
   // filename.

   if (!pFileName) {
     
std::cerr << "Couldn't create temp file name.\n";
     
return(EXIT_FAILURE);
   }

   std::cout << "The temp file name is: " << pFileName << '\n';

   std::ofstream of(pFileName);

   if (of) {
     
of << "Here is some temp data.";
     
of.close();
   }

   std::ifstream ifs(pFileName);
   std::string s;

   if (ifs) {
      ifs >> s;

      std::cout << "Just read in "" << s << ""\n";
      ifs.close();
   }
}

But there is something important you should know about tmpnam. It has a race condition whereby more than one process may generate the same filename if one calls tmpname and the other calls tmpname before the first process opens the file. This is bad for two reasons. First, a malicious program can do this to intercept the data in a temporary file, and second, an unsuspecting program can get the same filename and simply corrupt or delete data.

Please check back next week for the continuation of this article.


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

blog comments powered by Disqus
C++ ARTICLES

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 



© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 11 - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials