Random accesses to a file. The file posted here contains a formatted list of 999
ID: 670153 • Letter: R
Question
Random accesses to a file.The file posted here 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.
You are strongly recommended to 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.
You can 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.
Requirements:
You are not allowed to create or use any other files except the single input file.
You must use seekg() or seekp() to directly identify the insertion point to insert the new numbers.
It's acceptable to hardcode the input file name and implement everything in the main() function. However, it's preferred to create a separate function that handles the insertion of new numbers.
Explanation / Answer
#include <bits/stdc++.h>
using namespace std;
int main(){
ifstream infile;
infile.exceptions ( std::ifstream::failbit | std::ifstream::badbit );
try {
infile.open("input.txt");
infile.seekg(0, is.end);
int length = infile.tellg();
infile.seekg(0, is.beg);
char* buffer = new char[length];
infile.read(buffer,length);
infile.close();
int t = 6000*5;
ofstream outfile;
outfile.open ("test.txt");
outfile.write (buffer,length);
outfile.seekp(pos-t);
outfile.write("7777 ",5);
outfile.close();
}
catch (std::ifstream::failure e) {
std::cerr << "The File ---- input.txt ---- is not Here ";
}
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.