So I'm reading in words from a text file. I start off by reading each line into a buffer string and then set a for loop to look for a space character or the newline character (as such would indicate the end of the word).
Then I get the strlen, allocate memory for a dynamic string in a WORD struct that I have defined, and copy it over.
My only problem now is getting rid of that newline character for the words that end with it.
Code:
void getData ()
{
FILE *fp1;
char buf[BUFSIZ], *pFirst, *pLast, *pTemp;
int length, i, temp_length;
WORD *tempw;
//Open file
fp1 = fopen(FILE1, "r");
if(!fp1){
printf("Error opening file!\n");
system("pause");
exit(101);
}
//Read text from file
while(fgets(buf, sizeof(buf), fp1)){//Read full line into buffer string
length = strlen(buf);
//printf("(%d)%s", length, buf);
if(length > 1){//Check for lines with text
pFirst = &buf[0];
for(i = 0; i < length; i++)
{
pLast = &buf[i];
if(*pLast == ' '){//Check for spaces
//printf("%d ", i);
tempw = createWord();
temp_length = strlen(pFirst) - strlen(pLast);
tempw->word = (char*) calloc(temp_length + 1, sizeof(char));
strncpy(tempw->word, pFirst, temp_length);
printf("%s (%d)\n", tempw->word, strlen(tempw->word));
pFirst = pLast + 1;//Reset initial pointer
}
if(*pLast == '\n'){//Check for end of line
//printf("%d ", i);
tempw = createWord();
temp_length = strlen(pFirst) - strlen(pLast);
pTemp = strchr(pLast, '\n');
if(pTemp)
*pTemp = '\0';
tempw->word = (char*) calloc(temp_length + 1, sizeof(char));
strncpy(tempw->word, pFirst, temp_length);
printf("%s (%d)\n", tempw->word, strlen(tempw->word));
}
}
}
}
return;
}
I noticed that some of the lines in the text files have one or two space characters before the newline. For some reason it goes by undetected and the condition for a terminating newline character is executed..
Code:
This is a sample.
This line contains a space before the newline.
This one doesn't.
This line contains two such characters before the newline.
End
Any and all feedback is appreciated
JeanErmand