0

I'm trying to get a string to copy everything on a .txt file. I don't care about returns or anything fancy, I just need everything ever typed on the file.

Here I have a .txt file called Default.txt.

x:-100
y:-30
z:30
w:100

It is in a folder located in my project folder, where I keep all my .cpp and .h files.

Macintosh HD/.../Project/Text_Files/Default.txt

Here is my code for putting it into a string (well, technically it's not my code).

using namespace std;

string TextFileToString(string filename)
{
    string line;
    stringstream dosString;
    ifstream inFile;
    inFile.open (filename.c_str());

    while(std::getline(inFile, line))
    {
        dosString<<line<<"\r\n";
    }

    return(dosString.str());
}

// In my main function

string s = TextFileToString("Default.txt");
cout << s;

Why won't this work? I've looked up several other solutions and they all are something like this. Is it because the file path needs to be more than "Default.txt"? I don't know. Please help!

  • possible duplicate of [Read file-contents into a string in C++](http://stackoverflow.com/questions/2912520/read-file-contents-into-a-string-in-c) – Borgleader Feb 21 '15 at 23:24
  • 1
    Please clarify "won't work". What happened when you used the debugger? – Thomas Matthews Feb 21 '15 at 23:24
  • When you only supply a filename you're asking to open a file in the current working directory. That may or may not be where the file is located. If you're running the application from that directory it probably is. If you're running it from an ide or debugger then there's probably a way to set the working directory there. You should always check if the open succeeded or not. – Retired Ninja Feb 21 '15 at 23:25
  • 1
    It certainly wouldn't work if the file weren't successfully opened, which is unfortunately never checked. Are you running this from the Xcode UI ? If so, the working directory at runtime may not be what you think it is, and some schema adjustments may be needed. [See here for one-such setup method](http://stackoverflow.com/questions/14476655/code-runs-perfect-in-g-but-not-in-xcode-cannot-find-file/14478210#14478210). – WhozCraig Feb 21 '15 at 23:32
  • @ThomasMatthews: "won't work," meaning the string is empty. Sorry about that. – Liam Wofford Feb 22 '15 at 14:37
  • @RetiredNinja: How do I change which directory/folder I'm working with to find the file? – Liam Wofford Feb 22 '15 at 14:38

0 Answers0