/* This program demonstrates: * 1. Working with files * 2. Working with files and structures * * * C++ programs can interct with files - read data from files instead fo the keyboard * and print data to files instead of the terminal/screen * To work with files, * 1. Create the file variables - > ifstream for input (cin), ofstream for output (cout) * 2. open a file with the file variable -> check if ok * 3. Use the file, just like cin/cout * 4. close them */ #include #include #include using namespace std; //Declaring the Movie structure. struct Movie { string name, director, rating; double collect, runtime; int year; }; //Function involving a stream variable - they always pass by reference void printMovies(ofstream &out, Movie arr[], int num); int main() { /* To open an input file, that is, a file that contains data we need to * read into our program, a la cin, we need a variable of type ifstream * Similarly, to open an output file, that contains data that we are * producing in the program, we need a variable of type ofstream. */ ifstream input; ofstream output; input.open ("numbers.txt"); // open the filename given by the user. output.open("total.txt"); if(!input) { cout<<"Unable to open input file"<> val; sum = sum + val; } // Write to the output file instead of the screen. Works like cout output << "The sum is "<< sum << endl; } // once we are done using the file, we have to close the files input.close(); output.close(); char inName[30], outName[30]; /* We can read in the filename from the user. If we do this, * it has to be a c-string. * Since c++ doesn't like file names with spaces, we can just use >> * instead of getline */ cout<<"Enter the input file name: "; cin>> inName; cout<<"Enter the output file name: "; cin>> outName; /* This part of the program demonstrates how to read in values from * a file into a dynamically allocated array of structures. * We create a Movie structure. * The first line of the input file is the number of Movie records. * Every other line has the following format: * Name # Box Office Collection # Runtime # Year # Director # Rating * The # character is used as a separator, to let us know where one element ends and the other begins. */ input.open(inName); output.open(outName); bool opened = true; // We can also use this to ensure the files were opened correctly if(!input) { opened = false; cout<<"Unable to open input file"<> numRecord; mArray = new Movie[numRecord]; //create the dynamic array input.ignore(); //gets rid of newline after number char pound; // a char to read the separator character for(int i=0; i> mArray[i].collect >> pound >> mArray[i].runtime >> pound >> mArray[i].year >> pound; getline(input, mArray[i].director, '#'); getline(input, mArray[i].rating, '\n'); } cout<<"Inputs processed successfully"<