Hello All,
I am trying to write a C program that reads a text file and output unique words sorted alphabetically using /usr/bin/sort. All non-alphabetic characters serves as delimiters and are discarded. I am having a problem just parsing the text file into words, getting SEG FAULTS. dbx gives error: program terminated by signal SEGV (no mapping at the fault address). Error is generated by this line: strcat(word, (char *)tolower(c)); Any suggestions would be greatly appreciated. Code below:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <errno.h>
#include <sys/wait.h>
#include <ctype.h>
#include <string.h>
int main(int argc, char *argv[]){
int i=0;
pid_t child_pid;
char *word, c;
if(argc != 3){
usage();
exit(1);
}
FILE *input = fopen(argv[2], "r");
if(input == NULL){
printf("File '%s' does not exist or could not be accessed.\n", argv[2]);
exit(1);
}
word = (char *)malloc(100);
while((c = fgetc(input)) != EOF){
while(!isalpha(c) && !isspace(c))
c = fgetc(input);
if(isalpha(c)){
strcat(word, (char *)tolower(c));
//word += c;
}
else{
puts(word);
free(word);
}
}
fclose(input);
return 0;
}
void usage(){
printf("usage: uniqify n filename\nn is the number of sorters to use and filename is the textfile to sort\n");
}