Using text files to write to arrays

I know that its possible to write and retrieve information to a text file from code, but I don't have a clue how to do any of that. I am trying to fill a huge array, but It takes up a lot of space in my code and a lot of time. I know that there is no way that I'll be able to avoid typing up all the information but I was wondering how I could put all the data in a separate text document and then fill the array by retrieving the data in the code.
Here's a pretty quick but still accurate tutorial: http://www.cplusplus.com/doc/tutorial/files/
I understand reading and writing to files, but how do I create the file. Do I have to create the file before I can read or write to it, or do I create the file within the code?
Obviously a file has to be there before you can read from it, but if you try to write to a file that isn't there then std::ofstream creates it.
So I can write a file by trying to access one that doesn't exist, then I can go back and send information back to my variables using getline (myfile, variablename)? Also, I am trying to make code that will allow a user to enter the name of their file but it won't accept a variable in myfile.open(). What can I do to go around that.
Last edited on
[small]GRex2595 wrote:
... but it won't accept a variable in myfile.open().

Sure it will, it just needs to be a char array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <fstream>

void pause()
{
    std::cin.sync();
    std::cin.ignore();
}


int main(int argc, char *argv[])
{
    std::string Name = "";
    
    std::cin >> Name;
    
    std::ifstream File(Name.c_str(), std::ios_base::in);
    
    while(File >> Name)
    {
        std::cout << Name << ' ';
    }
    
    File.close();
    pause();
    return EXIT_SUCCESS;
}

Tested and working. Sorry I don't like to use the std Namespace.

EDIT: Note that here I pass the name of the file to the constructor. If you want to use the "open()" member function on a preexisting object then you would simply use Name.c_str() as the argument at that point in the code.
Last edited on
Topic archived. No new replies allowed.