0

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 by Nick Evan: Fixed formatting

4
Contributors
4
Replies
6
Views
6 Years
Discussion Span
Last Post by rajina
0

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

0

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 by sirio.bm: n/a

0

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 by Dani: Formatting fixed

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.