Week4
Programming Assignment 2
- Extension: Due 11/7 11:55pm, don't be late!
- Environment Variables
- "setenv VARIABLE_NAME value" to set environment variables
- footprints will be found in /home/cs40at/footprint
- available as a third parameter of main as a char* array
- or use getenv()
- Streams
- filestream - fstream, string stream - sstream
env.c
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main (int argc, char* argv[], char* envp[]) {
string filename1, filename2;
fstream* filestream = new fstream();
string curline;
string file_contents;
// print out all the environment variables
for(int i=0; envp[i] != NULL; i++) {
cout << envp[i] << endl;
}
// get the value of a single environment variable
cout << getenv("HOME") << endl;
filename1 = filename2 = getenv("HOME");
filename1 += "/foo";
filename2 += "/bar";
// filestream operations
filestream->open(filename1.c_str(), fstream::in);
while (getline(*filestream, curline)) {
cout << curline << endl;
file_contents += curline;
}
delete filestream;
// a new filestream is needed for a new file
filestream = new fstream();
filestream->open(filename2.c_str(), fstream::out);
*filestream << file_contents;
delete filestream;
// parsing an integer
int one;
int two;
int three;
string onetwothree = "1 2 3";
stringstream* ss;
ss = new stringstream(onetwothree);
*ss >> one >> two >> three >> onepointone;
cout << "one=" << one << " two=" << two << " three=" << three << endl;
}