-1

I'm looking for a way to way to read files in C++ I can write files, but here's where I'm stuck at:

ifstream readfile;
readfile.open("C:/Users/Crazy/Desktop/Useless.txt")

I 've seen people do things such as:

#include <iostream>
#include <fstream>

using namespace std;

int main() {

    ifstream myReadFile;
    myReadFile.open("text.txt");
    char output[100];
    if (myReadFile.is_open()) {
        while (!myReadFile.eof()) {

            myReadFile >> output;
            cout << output;

        }
    }
    myReadFile.close();
    return 0;
}

But in

char output[100];

I want the whole thing read.

Also, I just want to only read it, not to check if it's already open, not to, check for errors. I just want to read the whole thing, and the whole thing only.

sg7
  • 5,365
  • 1
  • 30
  • 39
Katido 622
  • 11
  • 6
  • 3
    For what it's worth, [the people writing that code are wrong](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong). – Lightness Races in Orbit Mar 20 '18 at 22:32
  • 2
    I don't understand. If you don't want to check if the file is already open, what do you want to happen if it isn't? If you don't want to check for errors, what do you expect to happen if there is an error? You can't get around these possible eventualities by putting your fingers in your ears and singing "la la la la"... – Lightness Races in Orbit Mar 20 '18 at 22:33
  • Lightness Races in Orbit, I'll open it the first thing I do, and close it at the end. If I have an error, well, I test every possible thing I can think of, and if I have an error fix it, but if I do have an error, I can work how to work around it. – Katido 622 Mar 20 '18 at 22:44
  • @Katido622: LRO means an error like "file does not exist", not "bug in your program". You have to decide how to handle run time errors. – Martin Bonner supports Monica Mar 21 '18 at 10:11
  • Hmm... I could handle that.. I think. – Katido 622 Mar 21 '18 at 20:47

1 Answers1

1

If you want to read the entire file into a variable you'll need to:
1. Determine size of file in characters.
2. Use std::vector and declare a vector of that size,
or use the new operator and dynamically allocate a char array.
3. Use ifstream::read to read in the entire file.
4. Close the ifstream.
5. Remember to delete the char buffer.

I recommend using an OS API to determine the file length.

Edit 1: Example

#include <iostream>
#include <fstream>
#include <vector>
std::ifstream my_file("my_data");
my_file.seekg(0, std::ios_base::end); // Seek to end of file.
const unsigned int file_length = my_file.tellg();
my_file.seekg(0);
std::vector<char> file_data(file_length);
my_file.read(&file_data[0], file_length);
Thomas Matthews
  • 52,985
  • 12
  • 85
  • 144