/* File: util.c Author: Xiuwen Liu Created on: Sept. 25, 2003 Description: It includes a set of functions used by the main and other functions.. Compile: See makefile */ #define UTIL_SOURCE_C_C #include "util.h" int Count_Item_InFile(char *fname) { FILE *fp; int nitem, tmp; char *temp_buf; struct stat stat_buf; fp = fopen(fname,"rb"); if (fp == NULL) { fprintf(stderr,"Cannot open file \"%s\" for reading.\n", fname); return -1; } fstat(fileno(fp), &stat_buf); /* To be safe, we allocate a large enough buffer */ temp_buf =(char *)malloc(sizeof(char)*(stat_buf.st_size+1)); nitem = 0; do { if (fscanf(fp,"%d%s", &tmp, temp_buf)==2) { nitem++; } else { break; } } while(1); fclose(fp); free(temp_buf); return nitem; } int Read_Items_FromFile(char *fname, WORD_INFO *words, int nitem) { FILE *fp; int item_read; char *temp_buf; struct stat stat_buf; fp = fopen(fname,"rb"); if (fp == NULL) { fprintf(stderr,"Cannot open file \"%s\" for reading.\n", fname); return -1; } fstat(fileno(fp), &stat_buf); /* To be safe, we allocate a large enough buffer */ temp_buf =(char *)malloc(sizeof(char)*(stat_buf.st_size+1)); item_read = 0; do { if (fscanf(fp,"%d%s", &(words[item_read].category), temp_buf)==2) { words[item_read].word = (char *)malloc(sizeof(char)*(strlen(temp_buf)+1)); strcpy(words[item_read].word, temp_buf); item_read++; if (item_read >= nitem) break; } else { break; } } while(1); fclose(fp); free(temp_buf); return item_read; }