File Handling programs of C

Started by NAREN, Jun 14, 2008, 09:16 PM

Previous topic - Next topic

NAREN

File Handling programs of C




File Handling programs

This section contains programs demonstrating file handling and command
line arguments.

The following program reads a text file and counts how many times each
letter from 'A' to 'Z' occurs and displays the results.

#include
#include
#include

int count[26];

void main(int argc, char *argv[])
{
FILE *fp;
char ch;
int i;
/* see if file name is specified */
if (argc!=2) {
printf("File name missing");
exit(1);
}

if ((fp= fopen(agv[1], "r")) == NULL) {
printf("cannot open file");
exit(1);
}

while ((ch=fgetchar(fp)) !=EOF) {
ch = toupper(ch);
if (ch>='A' && ch<='Z') count[ch-'A']++;
}

for (i=0; i<26; i++)
printf("%c occurred %d times\n", i+'A', count);

fclose(fp);
}

This program uses command line arguments to read and display the
contents of a file supplied as an argument.
#include

#define CLEARS 12 /* constant */

main(int argc , char *argv[])
{
FILE *fp , *fopen();
int c;

putchar(CLEARS);

while ( --argc > 0 )
if ((fp=fopen(argv[1], "r"))==NULL)
{
printf("I can't open %s\n", argv[1]);
break;
}
else
{
while ((c= getc(fp)) !=EOF)
putc(c,stdout); /* display to the screen */
fclose(fp);
}
}

This program gives a further example of the use of argc & argv
#include
#include

main(int argc , char *argv[])
{
double a , b;

if (argc != 3) {
printf("Usage: add number number ...\n");
exit(1);
}

a = atof(argv[1]);
b = atof(argv[2]);

printf("%lf\n" , a + b);
}
nice games here