diff --git a/mygrep/mygrep.c b/mygrep/mygrep.c index 3b29892..0fadde9 100644 --- a/mygrep/mygrep.c +++ b/mygrep/mygrep.c @@ -15,10 +15,10 @@ int main(int argc, char *argv[]) { char *ofile = NULL; char *keyword = NULL; char *filename = NULL; - int c; + int c = getopt(argc, argv, "io:h"); ///< Get the options - // Get the options - while((c = getopt(argc, argv, "io:h")) != -1) { + /// Process the options + while(c != -1) { switch(c) { case 'i': iflag = 1; @@ -39,7 +39,7 @@ int main(int argc, char *argv[]) { } } - // Check if the required argument is there + /// Check if the required argument is there if(argv[optind] == NULL) { fprintf(stderr, "Mandatory argument 'keyword' missing.\n"); print_usage(); @@ -49,28 +49,28 @@ int main(int argc, char *argv[]) { filename = argv[optind + 1]; } - // Get user input if there is no input file defined + /// Get user input if there is no input file defined while(filename == NULL) { - size_t len; // Define an unsigned string length value + size_t len; ///< Define an unsigned string length value - if(getline(&filename, &len, stdin)) { // Read until new line + if(getline(&filename, &len, stdin) != -1) { ///< Read until new line check_for_string(filename, keyword, iflag, ofile); - filename = NULL; // Reset the input + filename = NULL; ///< Reset the input } } - // Get data from input file + /// Get data from input file if(filename != NULL) { - FILE *in; - if((in = fopen(filename, "r")) == NULL) { + FILE *in = fopen(filename, "r"); + if(in == NULL) { fprintf(stderr, "Error opening the file %s\n", filename); exit(EXIT_FAILURE); } size_t len; - char *line = NULL; // Define a pointer to hold our value + char *line = NULL; ///< Define a pointer to hold our value - // Read the file line by line and execute check_for_string for each line + /// Read the file line by line and execute check_for_string for each line while(getline(&line, &len, in) != -1) { check_for_string(line, keyword, iflag, ofile); } @@ -132,10 +132,10 @@ static void check_for_string(char *to_check, char *to_find, int iflag, char *ofi * If found, append haystack to the end of the file * Close the file **/ - FILE *out; + FILE *out = fopen(ofile, "a"); - // Check if the file was opened successfully - if((out = fopen(ofile, "a")) == NULL) { + /// Check if the file was opened successfully + if(out == NULL) { fprintf(stderr, "Error opening the file %s\n", ofile); exit(EXIT_FAILURE); }