I had this machine exercise on my EEE11 class, and boy, I am dealing with file I/O and pointers. Our lecture professor had discussed a little about pointers, and for the past two meetings we hadn't had a lecture class. Our lab instructor wasn't there last week, and so she gave us the machine exercise which will be checked this coming Tuesday.
Since I had no idea about opening files in C programming I had to do some research from my notes and my friends. Luckily they answered 2 out of 3 parts of the problem. The last one, well they'll be needing more help. After my research and coding I was able to finish all three parts, but I don't like the way I solved part three.
Part One was about printing out the contents of the text file.
Part One was about printing out the contents of the text file.
Part Two was about getting the number of characters and words in the text file.
And Part Three was about saving the words in the text file to a dynamic array without duplicates.
Part Three was definitely the hardest, and it took me hours to make it work. I wasn't satisfied with my work because it doesn't seem to be a dynamic array. It looked more like a double pointer to an array of strings. The strings are separated, so you can't access the next word with (**dbpt + k). You can access it only with *(*(dbpt + i) + j). Sorry if you don't get what I mean.
After a few more days I made it work, though I didn't use a double pointer anymore.
Here's a sneak peak of the function, it gets the filename, then stores in a dynamic array. Words are separated by the NULL character. The last character of the dynamic array is the End of File (EOF).This function lacks a function which removes repetitions. I removed it so people could work hard on removing the repetitions.
char *store(char *fp) {
FILE *fn = fopen(fp, "r");
char ch;
int i,j,x;
char *parse = malloc(1024);
char *array;
for(i=0,j=0,x=0;;) {
ch = fgetc(fn);
if(isalnum(ch)||ch=='-'||ch=='\'') {
*(parse+i) = tolower(ch);
i++;
} else {
if (i>0) {
*(parse+i)='\0';
i=0;
int q = strlen(parse) +1;
char *temp = realloc(array, (j+q+1)*sizeof(*array));
if (temp!=NULL) {
array = temp;
temp = NULL;
} else {
printf("Not enough memory!\n");
exit(1);
}
strncpy(array+j, parse, q);
j+=q;
x++;
}
}
if (ch==EOF) break;
}
fclose(fn);
free(parse);
*(array+j) = EOF;
return array;
}
I hope you understand C Programming Language. I haven't actually tested my program on Linux but it sure works on Dev-C++.
Questions? Comments? You know where to post it.
Search for definitions in the Internet quickly by reading this article.
No comments:
Post a Comment
Thoughts? Comments, Suggestions, or Just Wanna Say Hi? Post Here.