Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Become a C++ Expert!

Join 137,226 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,078 people online right now. Registration is fast and FREE... Join Now!





Writing Custom Data to a File

Creates a text file and writes custom or preexisting data to it.

Submitted By: KYA
Actions:
Rating:
Views: 251

Language: C++

Last Modified: June 14, 2008
Instructions: Implement whenever custom data needs to be written unencrypted to a simple text file. Based on how you input it, you can simply "reverse" the process for retrieval.

Snippet


  1. /*
  2. * Per request, this snippet shows how to create
  3. * an empty file to write data to. Could
  4. * be used to save game data or whatever inside a text
  5. * file to be opened later
  6. * KYA
  7. * June 3,2008
  8. */
  9.  
  10.  #include <iostream>
  11.  #include <string>
  12.  using namespace std;
  13.  
  14.  int main()
  15.  {
  16.      FILE* newFile;
  17.      char name [256];
  18.      
  19.      cout << "Enter data to be saved (string):";
  20.      fgets(name, 255, stdin); //collect input
  21.      newFile = fopen("gameSave.txt", "w"); //create file for writing
  22.      if (newFile == NULL){
  23.         cout << "Error creating new game save file";
  24.      }
  25.      else {
  26.           fputs(name, newFile); //writes data to file
  27.           fclose(newFile);
  28.      }
  29.      //Check directory for newly created file
  30.  }//end main
  31.  

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month