I'm reading a file in and adding each character to an array. I then break these characters down into words by removing spaces and other non-essential characters. Now, to work with each word individually, I'd like to add each word into it's own array. Is there any way to do this? I've attempted to add the memory location of the start of each word, but it keeps giving me the memory address of the very start of the array. The problem is, in the code below, the variable named 'buffer' overwrites itself with a new word with each iteration of the while loop. I need to be able to reference each word in order to push it into a linked list. Here's what I have so far:
#include <stdio.h>
#include <ctype.h>
int main(int argc, char **argv) {
char buffer[1024];
int c;
size_t n = 0;
FILE *pFile = stdin;
pFile = fopen(argv[1], "r");
if (pFile == NULL) perror("Error opening file");
else {
while(( c = fgetc(pFile)) != EOF ) {
if (isspace(c) || ispunct(c)) {
if (n > 0) {
buffer[n] = 0;
printf("read word %s\n", buffer);
n = 0;
}
} else {
buffer[n++] = c;
}
}
if (n > 0) {
buffer[n] = 0;
printf("read word %s\n", buffer);
}
fclose(pFile);
}
return 0;
}
If I give a file containing the characters "This is a test document that holds words for this exercise", the following is produced:
read word This
read word is
read word a
read word test
read word document
read word that
read word holds
read word words
read word for
read word this
read word exercise