私はCが初めてで、ポインターを理解しようとしています。
このプログラムは -i で動作しますが、数行後に segfaults が発生し、すぐに -f segfaults が発生します。
#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);
}