David K David K - 27 days ago 7
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";
my_input_file.open(filepath);


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

my_input_file.close();
my_output_file.close();


}
else
{
cout << "FAIL\n";
}

cin.get();
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?

thanks!

Answer

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.

Comments