User Tools

Site Tools


cplusplus:file_processing_examples

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revisionPrevious revision
Next revision
Previous revision
Last revisionBoth sides next revision
cplusplus:file_processing_examples [2017/02/08 20:51] – [Simple example] mithatcplusplus:file_processing_examples [2019/02/11 19:15] – [Using filenames] mithat
Line 60: Line 60:
 </file> </file>
  
-==== Filenames must be c_str in pre-C++11 ====+==== Using filenames ====
  
 <file c++ simple-file-write3.cpp>// This program writes data to a file. <file c++ simple-file-write3.cpp>// This program writes data to a file.
Line 79: Line 79:
     cin >> filename;     cin >> filename;
  
-    outfile.open(filename.cstr());   // associate file with file pointer object+    outfile.open(filename);            // associate file with file pointer object 
 +    //outfile.open(filename.c_str());   // convert filename to C-string if pre C++11
  
     if (!outfile)     if (!outfile)
Line 139: Line 140:
 #include <iostream> #include <iostream>
 #include <fstream> #include <fstream>
-#include <cstring>+#include <string>
 using namespace std; using namespace std;
  
Line 175: Line 176:
 #include <iostream> #include <iostream>
 #include <fstream> #include <fstream>
-#include <cstring>+#include <string>
 using namespace std; using namespace std;
  
Line 183: Line 184:
     int num1;     int num1;
  
-    ifstream infile;   // instantiate file pointer object +    ifstream infile;         // instantiate file pointer object 
-    infile.open(filename.c_str());   // associate file with file pointer object+    infile.open(filename);   // associate file with file pointer object
  
     if (!infile)     if (!infile)
-        cerr << "Error opening file." << endl; 
-    else 
     {     {
-        cout << "Reading from file ... " << endl;+        cout << "Error opening file." << endl; 
 +        return 1;  // exit program with error code 
 +    }
  
-        while (infile >> num1) +    cout << "Reading from file ... " << endl;
-        { +
-            cout << num1 << endl; +
-        } +
-        infile.close();    // close the file!+
  
-        cout << "Done!" << endl;+    while (infile >> num1) 
 +    { 
 +        cout << num1 << endl;
     }     }
 +    infile.close();    // close the file!
 +
 +    cout << "Done!" << endl;
  
     return 0;     return 0;
 } }
 </file> </file>
cplusplus/file_processing_examples.txt · Last modified: 2019/02/11 19:17 by mithat

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki