14k.wizard 14k.wizard - 1 month ago 17
C++ Question

How do I open a file in C++ using just the filename?

Its a bit of a chore for me when coding in java and c++ to have to get the file path and add in an extra '\' so the compiler is not confused. Does anybody know how I can go about doing in out file operations using just the file name?

Here is some sample code:

int main(){

char str[100];

ifstream inStream;
ofstream outStream;

inStream.open("pre-html.txt"); //fails to open without file path

if(inStream.fail()){
cout << "File failed to open";
exit(1);//exit(1) faster than exit(0)
}

//reads the data from the file
while(inStream >> str){
cout << str;
}

}

Answer

Does anybody know how I can go about doing in out file operations using just the file name?

Start your program in the same directory where your file exists.