Command line arguments in C

#include<stdio.h>
int main(int argc,char *argv[])
{
    FILE *fp;
    char c;
    if(argc==2)
    {
        fp=fopen(argv[1],"w");
        while((c=getchar())!=EOF)
        {
            putc(c,fp);
        }
        fclose(fp);
        fp=fopen(argv[1],"r");
        while((c=getc(fp))!=EOF)
        {
            printf("%c",c);
        }
        fclose(fp);
    }
    return 0;
}

How to run this program in linux?
I have tried these steps:

  1. open terminal in linux
  2. type the command ./a.out program_name file_name

Edited 3 Years Ago by Nick Evan: Fixed formatting

Did you compile the code ?
Did you specify the name of the executable when you were compiling the code ?If not the default name is a.out

to compile the code, (assuming you have gcc installed, if you aren't and are on ubuntu, a handy shortcut is running sudo apt-get install build-essential)

run gcc -o my_program my_program.c

then, run ./my_program

As a matter of interest, vim is a useful editor in these circumstances.

A few formatting notes: c source is usually in a name.c file (.cpp for C++), headers in a .h file. INDENT your code (for your own sake). Post your code INDENTED (by using the [code] button in the post editor) for our sake.

Best of luck.

Edited 6 Years Ago by sirio.bm: n/a

Command line arguments in C

#include<stdio.h>
int main(int argc,char *argv[])
{
FILE *fp;
char c;
if(argc==2)
{
fp=fopen(argv[1],"w");
while((c=getchar())!=EOF)
{
putc(c,fp);
}
fclose(fp);
fp=fopen(argv[1],"r");
while((c=getc(fp))!=EOF)
{
printf("%c",c);
}
fclose(fp);
}
return 0;
}

I have given name of the program cmdEx.c
And saved in one of the directory ,then opened terminal in the same directory.
typed command ./a.out cmdEx.c file.txt
Its working...
Thank you for your kind suggestions

./a.out program_name.c file_name.txt

Edited 3 Years Ago by Dani: Formatting fixed

This article has been dead for over six months. Start a new discussion instead.