C++
  Home arrow C++ arrow Page 4 - Focusing on C++ Files
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C++

Focusing on C++ Files
By: O'Reilly Media
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 3 stars3 stars3 stars3 stars3 stars / 2
    2008-10-30

    Table of Contents:
  • Focusing on C++ Files
  • 10.7 Copying a File
  • 10.8 Deleting or Renaming a File
  • 10.9 Creating a Temporary Filename and File

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    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.

       · This article is an excerpt from the book "C++ Cookbook," published by O'Reilly. We...
     

    Buy this book now. 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). Check it out today at your favorite bookstore. Buy this book now.

    C++ ARTICLES

    - 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++
    - Advanced File Handling with Streams in C++
    - File Handling and Streams in C++
    - The STL String Class







    © 2003-2010 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek