A file posted contains a formatted list of 9999 integers that are randomly gener
ID: 3673849 • Letter: A
Question
A file posted contains a formatted list of 9999 integers that are randomly generated in the range of [1,9999]. Each integer occupies one single line and takes 4 characters' space per line. Alternatively, you can think that each number takes 5 characters' space, four for the number and one for the newline character. Write a C++ program using the seekg() and seekp() functions to insert the numbers 7777 through 7781 between the 6000-th and 6001-st numbers of the input file. Below are a few useful tips:
The tellg() and tellp() functions return the position of the current character in an input stream or output stream, respectively.
Use the tellg() function to first learn about the starting position of each integer. This will help you locate the exact starting position to insert the new numbers.
Use the width() function to specify the number of characters you'd like an integer to occupy.
In addition to the "output" operator (<<), you can also use the write() function to write to a file.
Before you insert the numbers, you will need to first store all the numbers from the 6001-st number in an internal data structure, e.g., array. Otherwise, some of them will be overwritten.
Finally, always call the clear() function before calling the seekg() or seekp() function. Otherwise, you might encounter inexplicable behaviors.
Explanation / Answer
#include #include #include #include using namespace std; int main() { //vector numVector; int myArray[10000]; const int SKIP_NUM = 6000;//number in file to skip to int numBytes = 5;//bytes to be read in(4byte num + newline) int product = (numBytes * SKIP_NUM);//to be used with seekg() fstream file("file1.txt"); if (!file) { cout nextNum; if (file.fail()) { break; } numVector.push_back(nextNum);//subscript out of range } file.clear();//clear the file handles file.seekp(product); for (int i = 7777; iRelated Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.