Program 64) Write a program that will recieve a filename and a line of text as command line arguement and write the text to the file.
This program shows the use of command line arguments. The comman line is
F12_7 TEXT AAAAAA BBBBBB CCCCCC DDDDDD
EEEEEE FFFFFF GGGGGG
Each word in the command line is an argument to the main and therefore the statement
fp = fopen (argv [1], "w") ;
opens a file with the name TEXT. The for loop that follows immediately writes the remaining 7 arguments to the file TEXT.
PROGRAM
#inclyde <stdio.h>
main ( )
{
FILE *fp ;
int i ;
char word [15] ;
fp = fopen (argv [1], "w") ;
/* open file with name arg[1] */
printf ("\nNo. of arguments in
Command line = %d\n\n", argc) ;
for (i = 2; i < argc; i++)
fprintf (fp, "%s", argv[i]) ; /* Write to file argv[i] */
fclose (fp) ;
/* Writing content of the file to screen */
printf ("Contents of %s file\n\n", argv[1]) ;
fp = fopen (argv [1], "r") ;
for (i = 2; i < argc; i++)
{
fscanf (fp, "%s", word) ;
printf ("%s ", word) ;
}
fclose (fp);
printf ("\n\n") ;
/* Writing the arguments from memory */
for (i = 0; i < argc; i++)
printf ("%*s \n", i * 5, argv [i]) ;
}
Output
C>F12_7 TEXT AAAAAA BBBBBB CCCCCC DDDDDD
EEEEEE FFFFFF GGGGG
No. of arguments in Command line = 9
Contents of Text file
AAAAAA BBBBBB CCCCCC DDDDDD EEEEEE FFFFFF
GGGGGG
C:\C\F12_7.EXE
TEXT
AAAAAA
BBBBBB
CCCCCC
DDDDDD
EEEEEE
FFFFFF
GGGGGG
No comments:
Post a Comment