Hi,

Could anyone please tell me how can i input data either from a file or stdin.

If the file name is not specified the data can be read from the UNIX command prompt using stdin.

I know stdin is a file pointer but how to use it please explain??

Dani AI

Generated

As pointed out, the shell handles redirection — your program just needs to read from stdin when no filename is given, or open the filename passed on the command line. is right that this is a C++ forum, but using a FILE* in C++ is fine when your assignment or legacy code calls for it. The robust pattern is: scan argv[], treat arguments beginning with - as options, collect the non-option operands, and (when the grammar says the last operand is the input file) use that last operand as the filename; otherwise fall back to stdin.

Example FILE* pattern (safe, simple parsing and fallback to stdin):

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <string>

int main(int argc, char* argv[]) {
    std::vector<std::string> operands;
    bool displayAll = false;

    for (int i = 1; i < argc; ++i) {
        if (argv[i][0] == '-') {
            if (strcmp(argv[i], "-displayall") == 0) displayAll = true;
            else { fprintf(stderr, "Unknown option: %s\n", argv[i]); return 1; }
        } else {
            operands.emplace_back(argv[i]);
        }
    }

    FILE* in = stdin;
    FILE* opened = nullptr;
    if (!operands.empty()) {
        opened = fopen(operands.back().c_str(), "r");
        if (!opened) { perror(operands.back().c_str()); return 1; }
        in = opened;
    }

    char buf[4096];
    while (fgets(buf, sizeof buf, in)) fputs(buf, stdout);

    if (opened) fclose(opened);
    return 0;
}

Notes and tips

  • Use fopen + fgets/fputs (above) for portability; use POSIX getline if you need arbitrary-length lines.
  • If you prefer to keep existing stdin-based code, call freopen(filename, "r", stdin) when a filename is supplied — that way the rest of the code can continue to read from stdin (or cin if you call std::cin.rdbuf() on the FILE* handle).
  • Always check fopen results and print errors to stderr (use perror for useful diagnostics). Close only files you opened (don’t fclose(stdin) unless you explicitly replaced it).
  • For your homework grammar (options anywhere, optional file), collecting non-option operands and taking the last as the filename will match the spec and behaves well with both ./hw2 ... file and ./hw2 ... < file.

Recommended Answers

All 3 Replies

you mean something like this? You can either provide a file name on the command line or redirect a file into the program like this: myprog <main.cpp

void foo(istream &in)
{
    string line;
    while( getline(in, line) )
        cout << line << '\n';
}

int main(int argc, char* argv[])
{
    if( argc == 2)
    {
        ifstream in(argv[1]);
        if( in.is_open() )
            foo(in);
    }
    else
        foo(cin);
}

yes that is what i wanted to either provide a file name on the command line or redirect a file into the program.

But i have not used ifstream for opening the file.I have used a file pointer and opened the file using fopen.

could you please tell me how to redirect the file using FILE pointer.

My assignment says like this:

The commandline syntax for hw2 is as follows:

hw2 bst [-displayall] [file]
hw2 bst_delete [-displayall] string1 string2 ... stringN file
hw2 avl [-displayall] [file]
hw2 avl_delete [-displayall] string1 string2 ... stringN file

Square bracketed items are optional. [BC: updated 2/13/2010] If an optional file is not specified, your program should read from stdin. You must follow the UNIX convention that commandline options can come in any order. (Note: a commandline option is a commandline argument that begins with a - character in a commandline syntax specification.) Unless otherwise specified, output of your program must go to stdout and error messages must go to stderr.

This is the C++ forum, not the C forum. You cannot expect C answers in a C++ forum.

Nevertheless, AD did answer your question sufficiently. The answer works the same way, except you use a FILE* instead of an istream.

If you can use FILE*s, you can do it. Please pay attention.

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.