简体   繁体   中英

Saving a txt file into a folder in the same folder as the cpp file in C++

I want to make a program that can save a text file into a folder that is in the same folder as the cpp file without having to write down the full path, as the location of the cpp file may be changed.

Example:

I have my cpp in a file called CppFileLocation on my desktop: C:\\Users\\user\\Desktop\\CppFileLocation\\file.cpp

I want it to save the text file into a folder called CppFileHistory : C:\\Users\\user\\Desktop\\CppFileLocation\\CppFileHistory\\textfile.txt

It should work without writing the full path: C:\\Users\\user\\Desktop\\CppFileLocation in the cpp file.

I have tried this:

#include <cctype>
#include <iostream>
#include <string>
#include <fstream>
#include <ctime>
using namespace std;

#pragma warning(disable : 4996)

int main()
{
    string filename = "textfile.txt";

    ofstream saveloc;
    saveloc.open("\\CppFileHistory\\" + fileName);
    saveloc << "this is some text.\n";
    saveloc.close();
}

Thank you for reading.

Try this:

 saveloc.open(".\\CppFileHistory\\" + fileName);

with the dot .

But I can't guarantee to work. Because a C++ program is supposed to be compiled into an executable, then run the executable. When the executable is run, you basically free to pick its "current working directory". What the above code does is, from the current working directory . , find a subdirectory CppFileHistory , and in it, open the fileName .

What you posted in the question seems to me that you will run the executable under CppFileLocation . Hence I suggest the above change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM