Code:
#include <getopt.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#define BUFFSIZE 1000000
long read_file(char *filename, char *text ) {
FILE *fp = fopen(filename, "r");
long size = 0;
int len = 0;
if (fp == NULL) {
fprintf(stderr,"Error could not open file: %s\n", strerror);
return -1;
}
if (fseek(fp, 0L, SEEK_END) == 0) {
size = ftell(fp);
if (size == -1) {
fprintf(stderr,"Error could not open file: %s\n",strerror);
return -1;
}
if (fseek(fp, 0L, SEEK_SET) != 0) {
fprintf(stderr, "Error rewinding to start of file: %\n",strerror);
return -1;
}
len = fread(text, sizeof(char), (size_t)size, fp);
if (len == 0) {
fprintf(stderr, "Error reading file into memory: %s\n", strerror);
return -1;
} else {
text[++len] = '\0';
}
}
(void)fclose(fp);
return size;
}
int chars_chars(char* buffer, int size) {
return size / sizeof(char);
}
int words_words(char* buffer, int size) {
int word_count = 0;
int x = 0;
char prev_char;
for(x = 0; x < size; x++)
{
if((buffer[x] == '\n' || buffer[x] == '\t' || buffer[x] == ' ')&&
(prev_char != '\n' && prev_char != '\t' && prev_char != ' ' && prev_char !="NULL"))
word_count++;
prev_char = buffer[x];
}
return word_count;
}
int lines_lines(char* buffer, int size) {
int line_count = 0;
int x = 0;
for(x =0; x < size; x++)
{
if(buffer[x] == '\n')
line_count++;
}
return line_count;
}
int main (int argc, char* argv[]){
int filesize = 0;
int print_chars = 0; int lines_count = 0;
int print_words = 0; int chars_count = 0;
int print_lines = 0; int words_count = 0;
int next_opt;
char* filename = "/usr/share/dict/words";
char filecontents[BUFFSIZE];
const char* const short_opt = "hcwlf";
const struct option long_opt[] =
{
{ "help", 0, NULL, 'h' },
{ "chars", 0, NULL, 'c' },
{ "words", 0, NULL, 'w' },
{ "lines",0, NULL, 'l' },
{ "file", 1, NULL, 'f' },
{ NULL, 0, NULL, 0 }
};
do {
next_opt = getopt_long (argc, argv, short_opt,long_opt, NULL);
switch (next_opt) {
case 'h':
printf ("-h --help Display this usage information.\n"
"-c --chars Print number of characters in FILENAME.\n"
"-w --words Print number of words in FILENAME.\n"
"-l --lines Print number of lines in FILENAME.\n"
"-f --file FILENAME Read from file.\n");)
break;
case 'c':
print_chars = 1;
break;
case 'w':
print_words = 1;
break;
case 'l':
print_lines = 1;
break;
case 'f':
filename = optarg;
filesize = read_file(filename, filecontents);
break;
}
}
while (next_opt != -1);
filesize = read_file(filename, filecontents);
lines_count = lines_lines(filename, filecontents);
chars_count = chars_chars(filename, filecontents);
words_count = words_words(filename, filecontents);
if(print_lines == 1)
printf("%i\n", lines_count);
if(print_chars == 1)
printf("%i\n", chars_count);
if(print_words == 1)
printf("%i\n", words_count);
}
Any help with this would be greatly appreciated!