Code:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
FILE *read_file;
char ch;
int x = 0, i;
char word[32]; // word storage
char *address;
read_file = fopen(argv[1],"r"); // open file where specified
if(read_file == NULL) {
printf("Error reading file\n");
return 1;
}
while( (ch = fgetc(read_file)) != EOF) {
if(isalpha(ch)) {
x = 0;
while(isalpha(ch)) {
word[x] = ch;
x++;
ch = fgetc(read_file);
}
word[x] = '\0';
address = (char *)malloc(x);
for(i=0 ; i<x ; i++) { // copy word to allocated area
*(address+i) = word[i];
}
// print the word, just for now.
for(i=0 ; i<=x ; i++) {
if(*(address+i) == '\0')
putchar('\n');
else
printf("%c", *(address+i));
}
} else {
// A non alphabetical char was encountered.
// I suppose that I allocate more memory for the next word here
// not sure how to do it
// allocate_memory()
continue;
}
}
// sort_words();
// write_to_file();
return 0;
}
This code works, it just prints the words the file has, one by line, but it prints them from the allocated data. Now, from where am I going to get all the pointers so that I could sort them?
And one other thing, take away the 'x=0;' assignment in line 20. Something funny happens, it outputs one word every line, but it outputs the word before it too. Example:
Code:
word1
word1word2
word1word2word3
Edit:
I found out why hehe. The word[] buffer will overflow anyways.. Since the x never initialize, then word will contain both words, the current one and the one before it.