Open file, not in folder

how do you open a file with the complete location, rather then the name of the file, and have it in the folder as the program?
I have this code, to drag a file onto it, but I get errors, what is wrong with it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{
    string file_source = pszArgs[1];
    cout << "Loading file from: " << file_source << "\n";
    ifstream file(file_source);
    string line;
    getline(file_source, line);
    cout << line;
    system("PAUSE");
    return 0;
}
In Win32 API use GetModuleFileName to get your program's location and name. Remove the .exe name at the end and you have the program's location. Add to the location the filename you want to write then open the file for writing.
Huh... I don't really understand what you said. Could you please explain it to me in plain english?
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{
    string file_source = pszArgs[1];
    cout << "Loading file from: " << file_source << "\n";
    ifstream file(file_source.c_str());
    string line;
    getline(file, line);
    cout << line;
    system("PAUSE");
    return 0;
}


The parameters that are needed by the ifstream constructor is a c-style string. You can use the c_str() method of the string class to convert to a c-style string, or you could just define a c-style string variable at the beginning of your code so you don't have to do a conversion:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <string>
#include <fstream>
using namespace std;

int main(int nNumberofArgs, char* pszArgs[])
{
    char* file_source = pszArgs[1];
    cout << "Loading file from: " << file_source << "\n";
    ifstream file(file_source);
    string line;
    getline(file, line);
    cout << line;
    system("PAUSE");
    return 0;
}


notice that in the code above, I have declared a char* instead of a string. A char* in c++ is a c-style string.
Hope this helps!
Matt
Last edited on
Thank you very much! :) You don't know how much you have helped me!
Topic archived. No new replies allowed.