?
#include <stdio.h>
#include <stdlib.h> // strerror, errno
#include <string.h>
#define LINELEN_MAX 100
#define WORDLEN_MAX LINELEN_MAX
#define LINES_MAX 30
#define WORDS_MAX 1000
int is_wordseparator ( char c )
{
return isspace(c) || c == '.' || c == ',' || c == ';' ||
c == '!' || c == '?' || c == '\n';
}
void exit_on_error ( char* );
struct Word
{
char word [WORDLEN_MAX+1];
unsigned lines [LINES_MAX];
unsigned n;
}Word;
struct Wordlist
{
unsigned n;
struct Word words[WORDS_MAX];
}Wordlist;
struct Word* find_word ( struct Wordlist* pwlist, char* word )
{
unsigned i = 0;
if ( word == NULL || pwlist->n == 0 )
return NULL;
while ( i < pwlist->n )
{
if ( 0 == strcmp ( word, pwlist->words[i].word ))
return &pwlist->words[i];
i++;
}
return NULL;
}
int have_line_nr ( struct Word* pw, unsigned line_nr )
{
unsigned i = 0;
while ( i < pw->n )
if ( pw->lines[i++] == line_nr )
return 1;
return 0;
}
char* get_word ( char* line, char* word, int size )
{
unsigned i = 0;
if ( line == NULL || *line == 0 )
return NULL;
memset ( word, 0, size );
while ( *line )
{
if (is_wordseparator(*line))
{
while (is_wordseparator(*line))
line++;
break;
}
if ( i == WORDLEN_MAX )
{
errno = 34; // ERANGE
exit_on_error ( "Word too long." );
}
word[i++] = *line++;
}
if( !*line )
return NULL;
return line;
}
int read_line (FILE* fp, char* buf, int size)
{
static int line_nr = 0;
memset(buf,0,size);
if ( NULL == fgets ( buf, LINELEN_MAX, fp ))
{
if (ferror(fp))
exit_on_error (NULL);
line_nr = -1;
}
return ++line_nr;
}
void register_word ( struct Wordlist* pwlist, char* word, unsigned line_nr )
{
struct Word* pw = NULL;
if ( pwlist->n == WORDS_MAX )
{
errno = 34; // ERANGE
exit_on_error ( "Structarray full." );
}
pw = find_word ( pwlist, word );
if ( pw && have_line_nr (pw, line_nr))
return;
if ( pw == NULL )
pw = &pwlist->words[pwlist->n++];
if ( pw->n == LINES_MAX )
{
errno = 34; // ERANGE
exit_on_error ( "Line-number-array full." );
}
pw->lines[pw->n++] = line_nr;
strcpy(pw->word, word);
}
void view_result ( struct Wordlist wlist )
{
unsigned i = 0, j = 0;
while ( i < wlist.n )
{
j = 0;
fprintf ( stdout, "%s ", wlist.words[i].word );
while ( j < wlist.words[i].n )
fprintf ( stdout, "%u ", wlist.words[i].lines[j++] );
puts("");
i++;
}
}
int main (void)
{
char* fname = "test.txt";
char line[LINELEN_MAX+2] = {0};
char word[WORDLEN_MAX+1] = {0};
char* pline = line;
int line_nr = 0;
struct Wordlist wlist = {0};
FILE* fp = fopen ( fname, "rb" );
if ( fp == NULL )
exit_on_error ( fname );
while ( 0 != ( line_nr = read_line (fp, line, sizeof(line))))
{
pline = line;
while ( NULL != ( pline = get_word (pline, word, sizeof(word))))
{
if(*word)
register_word ( &wlist, word, line_nr );
}
if(*word)
register_word ( &wlist, word, line_nr );
}
view_result (wlist);
fclose(fp);
return 0;
}
void exit_on_error ( char* msg )
{
if ( msg )
fprintf( stderr, "%s %s\n", msg, strerror(errno) );
else
fprintf( stderr, "%s\n", strerror(errno) );
fcloseall ();
}
mfg,
cOuNtOr