SunRise wrote:
Hi
I am creating a C Program [ Turbo-C ] , to extract
only-Printable-characters from a file ( any type of file) and display
them.
Ple help me to fix the Errors & Warnings and explain how to use
Command-Line Arguments inside C program.
#include <stdio.h>
#include <ctype.h>
#include <process.h>
^^^^^^^^^^ There is no such standard header
void main()
^^^^ main always returns an int {
/*char *file1 = argv[1]; */
FILE *fp1;
fp1=fopen("c:\\tmp\\tmp\\CPUCount20.exe","r");
if ( fp1 == NULL ) /* WARNING is here */
{
/* printf("Error opening file : %s\n\n", file1); */
printf("Exiting ...\n");
exit(1) ;
^^^ The portable arguments for exit()
are EXIT_FAILURE, EXIT_SUCCESS, and 0 }
while( fp1 != EOF )
^^^ this, and all subsequent references to fp1 are nonsense. {
if( isprint(*fp1) ) /* Error(1) & Error(2) */
{
putc(*fp1,stdout); /* Error(3) & Error(4) */
}
fp1++;
}
printf(" ======= End of strings1 ======== \n\n");
Start by turning on all the warnings you can.
Then write this as a simple filter. You will then learn to get the
skeleton right:
/* filter version, using getchar() */
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int c;
while ((c = getchar()) != EOF)
if (isprint(c) || (c == '\n'))
putchar(c);
putchar('\n');
return 0;
}
Now, replace the call to getchar() with a call to fgetc(). This will
show you how to implement the processing loop with file for input:
/* filter version, using fgetc() */
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int c;
while ((c = fgetc(stdin)) != EOF)
if (isprint(c) || (c == '\n'))
putchar(c);
putchar('\n');
return 0;
}
Now, let's add the possibility of a single command line argument for the
input file's name. We must decide what to do when
1) the argument is missing
2) when the argument is present
3) when there are too many argumnents
Here I have chosen to modify the filter version so it will continue to
function without a command line argument:
/* version allowing either 0 or 1 command line arguments */
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int c;
/* test for too many arguments */
if (argc > 2) {
fprintf(stderr, "too many command line arguments.\n");
exit(EXIT_FAILURE);
}
/* handle exactly one argument by reopening stdin */
if (argc == 2)
if (!freopen(argv[1], "rb", stdin)) {
fprintf(stderr, "Could not open \"%s\" for input.\n"
"Bailing out ...\n", argv[1]);
exit(EXIT_FAILURE);
}
/* and if there is no argument, use existing stdin. */
while ((c = fgetc(stdin)) != EOF)
if (isprint(c) || (c == '\n'))
putchar(c);
putchar('\n');
return 0;
}
You could obviously modify this in other ways. For example, you could
decide to require the command line argument and decide to open a new
input file instead of reopening stdin. Then you would need to have a
FILE pointer:
FILE *fp;
and use fopen() instead of freopen
if (!(fp = fopen(argv[1], "rb")))
and replace fgetc(stdin) with fgetc(fp)
and change the handling of the case with no arguments.