hello there, I\'m having trouble even getting started on this. any help you can
ID: 3761548 • Letter: H
Question
hello there, I'm having trouble even getting started on this. any help you can give is appreciated. Assignment:
Write a program that reads a text file using binary mode file reading in C++. The program should prompt the user for the file path, then print out the file contents to the console. Open the file in binary mode and read the entire file contents using one statement into a char array. Then, in a loop, print one character at a time to the console from the char array
The following code can be used to accomplish this task.
Open the file in binary mode like this:
inFile.open(filePath.c_str(), ios::binary);
To get the file size, use the seekg and tellg operators like this:
inFile.seekg(0, ios_base::end);
int fileLen = inFile.tellg();
inFile.seekg(0, ios_base::beg);
The first line moves the file cursor to the end of the file. The second line reads the byte position at that current location. The third statement moves the file cursor back to the beginning of the file so the data can be read from the beginning.
After that, you can read the entire file contents into your char array in one statement then close the file:
inFile.read(charArr, fileLen);
inFile.close();
Explanation / Answer
#include <iostream>
#include <fstream>
using namespace std;
int main () {
streampos size;
string file
char * memblock;enter
cout << "enter the file name :";
cin >> file;
ifstream file ("file", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << "the entire file content is in memory";
delete[] memblock;
}
else cout << "Unable to open file";
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.