i would like to ask if this is the right way to use malloc or if i am doing anything wrong.
i just turned the page about structures a few days ago in the book i am using.
thanks for the time to comment.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
struct contents
{
int chars;
int digits;
int others;
};
void PrintUsage(const char *progname);
int main(int argc, char** argv)
{
int c;
int i;
int ch,digit,other;
ch=digit=other=0;
FILE *fp;
if( argc == 1 )
{
PrintUsage(argv[0]);
exit(EXIT_FAILURE);
}
struct contents *count=malloc(sizeof(count));
if(count == NULL)
{
errno=EINVAL;
perror(argv[0]);
exit(1);
}
for(i=1;i< argc;i++)
{
if((fp=fopen(argv[i],"r")) == NULL)
{
errno=EINVAL;
perror(argv[0]);
exit(EXIT_FAILURE);
}
while((c=fgetc(fp))!= EOF)
{
switch(c)
{
case '1':case '2':case '3':case '4':case '5':
case '6':case '7':case '8':case '9':case '0':
digit++;
count->digits++;
case ' ': case '\n': case '\t':
other++;
count->others++;
default:
ch++;
count->chars++;
}
}
/* it prints total of the files if more than 1 file is counted. for now its considered a feature :) */
fprintf(stdout,"nchar %d ndigit %d nother %d %s\n",ch,digit,other,argv[i]);
fprintf(stdout,"nchar %d ndigit %d nohter %d %s\n",count->chars,count->digits,count->others,argv[i]);
} /* end for loop*/
fclose(fp);
free(count);
count=NULL;
return 0;
}
void PrintUsage(const char *progname)
{
fprintf(stdout," usage: %s [file] \n"
"counts chars digits and others \n",progname);
}