Note:
#include <errno.h>
#define WORD_OUTSIDE 1 /* Word outside */
#define WORD_INSIDE 0 /* Word inside */
int main(int argc, char *argv[])
{
/* For getchar should not use char datatype, because it return EOF.
* The value for EOF is . */
int ch = 0, nc = 0, nl = 0, nw = 0, word_in_out;
FILE *fp_input = NULL;
if (argc <=1) {
printf("Give file name in the command prompt while executing the commmand: \n\n");
return 0;
}
fp_input = fopen(argv[1], "r");
if (fp_input == NULL) {
printf("Failed to open the file %d. \n\n", errno);
perror("Error:");
return 0;
}
word_in_out = WORD_OUTSIDE;
while ((ch = fgetc(fp_input)) != EOF) {
++nc;
if (ch == '\n') {
++nl;
}
if ((ch == ' ') || (ch == '\n') || (ch == '\t')) {
word_in_out = WORD_OUTSIDE;
} else if (word_in_out == WORD_OUTSIDE) {
++nw;
word_in_out = WORD_INSIDE;
}
}
printf("Total number of character = %d, Line = %d, word = %d \n",
nc, nl, nw);
return 0;
}
Total number of character = 28, Line = 5, word = 7
- For getchar should not use char datatype, because it may return EOF.
- The value for EOF is -1
Program:
#include <stdio.h>#include <errno.h>
#define WORD_OUTSIDE 1 /* Word outside */
#define WORD_INSIDE 0 /* Word inside */
int main(int argc, char *argv[])
{
/* For getchar should not use char datatype, because it return EOF.
* The value for EOF is . */
int ch = 0, nc = 0, nl = 0, nw = 0, word_in_out;
FILE *fp_input = NULL;
if (argc <=1) {
printf("Give file name in the command prompt while executing the commmand: \n\n");
return 0;
}
fp_input = fopen(argv[1], "r");
if (fp_input == NULL) {
printf("Failed to open the file %d. \n\n", errno);
perror("Error:");
return 0;
}
word_in_out = WORD_OUTSIDE;
while ((ch = fgetc(fp_input)) != EOF) {
++nc;
if (ch == '\n') {
++nl;
}
if ((ch == ' ') || (ch == '\n') || (ch == '\t')) {
word_in_out = WORD_OUTSIDE;
} else if (word_in_out == WORD_OUTSIDE) {
++nw;
word_in_out = WORD_INSIDE;
}
}
printf("Total number of character = %d, Line = %d, word = %d \n",
nc, nl, nw);
return 0;
}
Output:
velraj@velraj-HEC41:~/CProgram$ ./a.out newTotal number of character = 28, Line = 5, word = 7
No comments:
Post a Comment