David K David K - 1 year ago 121
C++ Question

Having trouble processing a file from my documents in my code?

I have searched for this around the web and here but I can't seem to figure out what I am doing wrong.

I am simply trying get better with file processing and c++.

For practice I am trying to grab a text file from a game folder and make a copy of it.

Here is my code (that can't access the file).

#include <fstream>

#include <iostream>
#include <string>

using namespace std;

int main()

//define / open files
ifstream my_input_file;
ofstream my_output_file;
string filepath = "C:/Users/David Laptop/Documents/my games/oblivion/RenderInfo.txt";

if (my_input_file.is_open())
cout << "opened\n";
my_output_file.open("output_file.txt", ofstream::trunc);
char c;
while (my_input_file)


cout << "FAIL\n";

return 0;

This seemed to work with both text files and .ini files when in the project directory but I am having issues properly getting to other directiorys?

Any ideas?


Answer Source

Your code is perfectly valid and it works - I tried it with my own file instead of yours, in the line

    string filepath = "C:/Users/David Laptop/Documents/my games/oblivion/RenderInfo.txt";

So you have not such file or it is not in the given path or you have not such path.

Correct it in that line and it will be OK.

Tip: Find your file in Windows Explorer, press (and keep pressing Shift) and right-click on this file. From the context menu then choose Copy as path and then paste it to your code. But be carefull - you have to change every backslash (\) to a forward slash (/) (as in your code) or use double backslashes (\\) instead of single one.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download