Search code examples
c++fstream

fstream point to a specific path (to desktop ex.)


I'm doing a little Cpp console application where i am comparing two files and see if they are different.

I want to know, how i can change the path to like C:\Users\%user%\Desktop\tekst1.txt Where do i do that? Because i have tried to google it, and i cant find it.

It an application from the book "Engineering problem solving with C++"

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

const string AFIL = "tekst1.txt";
const string BFIL = "tekst2.txt";
const char NEWLINE = '\n';


int main()
{
    char a, b;
    int linje = 1, forskellige = 0, linje_flag = 0;
    ifstream afil, bfil;

    afil.open(AFIL.c_str());
    if (afil.fail()){
        cerr << AFIL << " kan ikke åbnes\n";
        exit(1);
    }
    bfil.open(BFIL.c_str());
    if (bfil.fail()){
        cerr << BFIL << " kan ikke åbnes\n";
        exit(1);
    }

    afil.get(a);
    bfil.get(b);

    while ((!afil.eof()) && (!bfil.eof()))
    {
        if (a != b)
        {
            forskellige++;
            linje_flag = 1;
            while (a != NEWLINE && !afil.eof())
                afil.get(a);
            while (b != NEWLINE && !bfil.eof())
                bfil.get(b);
            cout << "Filerne er forskellige i linie: " << linje << endl;
        }

        if (a == NEWLINE)
        {
            linje++;
        }
        afil.get(a);
        bfil.get(b);

    }
    if ((afil.eof()) != (bfil.eof()))
    {
        cout << "Filerne er forskellige i sidste karakter: " << linje << endl;
        forskellige++;
    }
    if (forskellige == 0)
        cout << "Filerne er ens\n";


    afil.close();
    bfil.close();
    system("pause");
    return 0;
}

Solution

  • A quick n' dirty solution would be to change:

    const string AFIL = "tekst1.txt";
    const string BFIL = "tekst2.txt";
    

    To:

    const string AFIL = "C:\\Users\\%user%\\Desktop\\tekst1.txt";
    const string BFIL = "C:\\Users\\%user%\\Desktop\\tekst2.txt";
    

    You can also try reading up on changing the current working directory for your process (OS-specific, see this for a corresponding, simple Win32 API). Then, all such paths passed to fstream constructors would be relative to whatever you choose.