Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

in c++ What we want to do is to test our ability to write to a text file and lat

ID: 3889727 • Letter: I

Question

in c++

What we want to do is to test our ability to write to a text file and later read from the text file. Suppose we wrote a program like the following:

(just the main body)

   int n1 = 3;

   int n2 = 10;

   ofstream outFile;

   outFile.open(“test.txt”);

   outFile << n1 << endl;

   outFile << n2 << endl;

   outFile.close();

   ifstream inFile;

   inFile.open (“test.txt”);

   inFile >> n1;

   inFile >> n2;

   inFile.close();

   cout << “n1: “ << n1 << endl;

   cout << “n2: “ << n2 << endl;

If you ran this and it printed out 3 for n1 and 10 for n2, is this proof that your program correctly wrote to a text file and then read from it?   If you think so, try copying it and running it. (A copy and paste will need a few modifications. Why?) After it runs, try modifying the second “test.txt” to “text.txt” and see how it runs. What’s going on?

Write 4 very short C++ programs: one that opens a text file, write 2 integers to it, and closes it (basically the first part of the above), one that opens the text file you wrote to, reads the 2 integers from it and prints them out to the screen (basically the second part of above). The other two does basically the same thing but with a binary file, using write() to write to the binary file, and read() to read from the binary file. For read () and write() you can use the sizeof() function to get the size of an integer. Run the programs that write to the files first and then run the programs that read from them afterwards.

Open the two files you created using NotePad (or other simple text editor) and take screen shots of the contents.

Create a class with two public members: an integer and a double. Repeat 4 and 5, but instead of 2 integers, use 2 objects of your class (put in whatever values you wish). You can use sizeof() to get the size of your object.

Create an fstream to a binary file that you can both write to and read from. Write 5 objects of your class to your binary file. Then see if you can read them all back in order and print them to the screen. Next, see if you can retrieve the third object directly from the file by using seekg() and an offset from the file beginning of 2 object size.

Explanation / Answer

First, the value of n1 and n2 are written in a file named "test.txt"(if the file does not exist, it is automatically created).

Then, the same file is read and the values are stored in n1 and n2.

If we read the values from a file that does not exist(suppose text,tst instead of test.txt, as given), the values of n1 and n2 will remain unchanged, exaty what is happening in theis case.