Thread: File as command line argument

  1. #1
    Registered User
    Join Date
    Sep 2018

    File as command line argument

    Hello guys!
    I have a program that receives data from the stdin and prints the result on the stdout.
    Usually to run the program I do this.
    ./nameOfTheProgram < file.txt
    But now I want something different , I want to run the program like
    ./nameOfTheProgram file.txt (without the <),
    this new version receives the data file as a command line argument and prints the result of the stdout on a new file.
    How can I do this?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Do you know how to work with command line arguments?

    Do you know how to work with files for input/output?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Dec 2017
    #include <stdio.h>
    #include <stdlib.h>
    int main(int argc, char **argv) {
        if (argc != 2) {
            fprintf(stderr, "Usage: program FILENAME\n");
        FILE *fin = fopen(argv[1], "r");
        if (!fin) {
            perror("Error opening file");
        return 0;
    The best argument against democracy is a five minute conversation with the average voter. - Churchill

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. command line argument help
    By jwroblewski44 in forum C Programming
    Replies: 10
    Last Post: 05-10-2012, 09:55 PM
  2. use of command line argument
    By natrajdreams in forum C Programming
    Replies: 2
    Last Post: 04-19-2009, 11:07 AM
  3. command line argument
    By csit in forum C Programming
    Replies: 4
    Last Post: 09-19-2007, 11:35 AM
  4. command line argument
    By Lord CyKill in forum Linux Programming
    Replies: 1
    Last Post: 04-11-2003, 02:05 PM
  5. '*' as a command line argument
    By kooma in forum C Programming
    Replies: 6
    Last Post: 02-26-2002, 02:18 PM

Tags for this Thread