I am trying to use file name as a parameter to a program in DOS.

I know it can be done by changing the parameter to the main().

I do not understand the exact way.

I have developed a data compression and decompression utility, it works for a particular file name but I want to make it more user friendly.

Looking forward to get some help.

Dani AI

Generated

Short summary and practical steps that build on , and :

Accept the filename on the command line, validate it, and open it for reading (and create a sensible default output name if none given). Check the number of arguments, test that the path exists, handle spaces/quotes, and fail with a clear usage message when the caller forgets the filename.

Example (modern, robust skeleton):

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

int main(int argc, char **argv) {
    if (argc < 2) {
        std::cerr << "Usage: compress <input-file> [output-file]\n";
        return 1;
    }

    std::filesystem::path in = argv[1];
    if (!std::filesystem::exists(in)) {
        std::cerr << "Input not found: " << in << '\n';
        return 2;
    }

    std::ifstream fin(in, std::ios::binary);
    if (!fin) { std::cerr << "Cannot open input\n"; return 3; }

    std::filesystem::path out = (argc >= 3) ? argv[2] : (in.string() + ".cmp");
    std::ofstream fout(out, std::ios::binary);
    if (!fout) { std::cerr << "Cannot create output\n"; return 4; }

    // perform compression/decompression here
}

Notes and gotchas tied to this thread:

  • If the filename has spaces, call the program from the shell with quotes (e.g. "myprog.exe \"my file.txt\""); the runtime hands the full path as a single argv entry.
  • On POSIX shells the shell expands wildcards before your program runs; on Windows cmd.exe it does not — implement pattern expansion yourself using std::filesystem if you want to accept wildcards.
  • For full Unicode filenames on Windows consider wide-char entry points or CommandLineToArgvW; drag-and-drop and "Open with" pass the filename as an argument if your program is associated with the extension.

References for details and API behavior:

Recommended Answers

All 3 Replies

You mean something like this: int main(int argc, char *argv[]) ?
If so, google: c++ int main parameters for more info.

or a better search term is: command line arguments

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.