i have my file input
like this
ifstream inFile;
inFile.open(fileName.c_str());

and i cin >> fileName;
i want the output file name to be the input filename with .dat added to it
eg if fileName was c:/tmp/test.txt
i want the output to be c:/tmp/test.txt.dat

anyone know how i can do this everything ive tried isnt working

Dani AI

Generated

Both and were right: appending a suffix will give you the exact filename you described (for example, c:/tmp/test.txt.dat), and confirmed that solved the problem. A few extra notes and alternatives to avoid common pitfalls and to cover different needs.

If you want to replace the existing extension (so test.txt becomes test.dat) and you're using a modern compiler, use the filesystem path helpers (C++17+):

#include <filesystem>
#include <fstream>
#include <string>

namespace fs = std::filesystem;

std::string input;
std::getline(std::cin, input);   // allows spaces in paths
fs::path p(input);

// replace the extension with ".dat" (or add it if none)
p.replace_extension(".dat");

std::ofstream out;
out.open(p.string());            // open the output file
if (!out) { /* handle failure */ }

For older compilers (pre-C++17), do a safe manual replace of the extension:

std::string input;
std::getline(std::cin, input);

std::string outname;
size_t pos = input.find_last_of('.');
if (pos == std::string::npos)
    outname = input + ".dat";          // no extension: append
else
    outname = input.substr(0, pos) + ".dat"; // replace extension

std::ofstream out(outname.c_str());    // portable to older stdlibs

Troubleshooting tips: use std::getline if paths may contain spaces; check out.is_open() or out.fail() after opening; confirm you declared std::ofstream (correct variable name and scope); verify file-system permissions and working directory. For details on the path helper used above see std::filesystem::path::replace_extension.

Recommended Answers

All 5 Replies

try this:

string filename;

cin >> filename;

filename += ".dat";

outFile.open(filename.c_str());

doesnt seem to be working

Try this:

#include <sstream>
string filename;
stringstream ss;
cin >> filename;
ss<<filename<<".dat";
outFile.open(ss.str().c_str());

The first str() gets the string from the string stream and the c_str() you already know.
(fill in the name of your own output file for outFile)

After further consideration I'm not sure why CP's solution would not work. What was the specific error you were getting?

(fill in the name of your own output file for outFile)

Was incorrect, my apologies. I had meant to say the name of your output filestream for outFile.

that worked thanks alot

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.