I’m new to C, and I’ve been trying to figure out pointers.
This program works with -i but segfaults after a few lines and -f segfaults right away.
#include <stdio.h>
#include <string.h>
void search_and_print ( char pattern[], FILE* search_file );
int main ( int argc, char *argv[] ) {
const char TOO_MANY_VARIABLES[] = "Too many arguments from the command line!";
const char NOT_ENOUGH_VARIABLES[] = "\nUSAGE: a.out [-i] [-f filename] (Search Pattern)\n";
if (argc < 2) { printf(NOT_ENOUGH_VARIABLES); return(1);}
// If input
if (strcmp(argv[1],"-i") == 0) {
char *pattern = argv[2];
search_and_print(pattern, stdin);
}
// If file
if (strcmp(argv[1],"-f") == 0) {
char *pattern = argv[3];
// Check if file exists
// Open file
FILE *file = fopen( argv[2], "r" );
search_and_print(pattern, file);
fclose( file );
}
}
void search_and_print ( char pattern[], FILE* search_file ) {
// Read through file
const int MAX_CHARACTERS_PER_LINE = 1000;
char* line[MAX_CHARACTERS_PER_LINE];
while ( fgets(*line, MAX_CHARACTERS_PER_LINE, search_file) != NULL )
if ( strstr(*line, pattern) != NULL )
printf(*line);
}
You have quite a few bugs here.
defines an array of 1000 pointers, not characters.
fgets(*line, ...passes the first of those pointers, which is uninitialized, tofgets, most likely causing a segvio.The first argument to printf is a format. Never ever pass user input as the format, as this opens a huge security hole in your program … see http://en.wikipedia.org/wiki/Uncontrolled_format_string
You should use
fputs(line)orprintf("%s", line)(once you fix the declaration of line).You don’t return a value (except in the error case) … that results undefined behavior.
You should check whether this succeeds. If the file can’t be opened (e.g., it doesn’t exist), passing it to fgets results in undefined behavior.
This test isn’t sufficient for your -f case.