Thanks for the replies. The key was laserlight's last statement
Originally Posted by
laserlight
The xtni_words array has xtni_words_max elements. You should avoid accessing the array out of bounds by checking that xtni_num_words < xtni_words_max before using xtni_words[xtni_num_words].
Here is my solution...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdbool.h>
#include <ctype.h>
/* Windows filenames */
#define XTNI_FILENAME "In_Transactions.ofx" /* OFX */
#define XTNI_LINE_LEN 55
FILE *xtni;
char *get_xtni(unsigned int xtni_words_max, int xtni_line_num,
char xtni_words[])
{
static char xtni_line_cur[XTNI_LINE_LEN];
if (fgets(xtni_line_cur, XTNI_LINE_LEN, xtni) == NULL) {
return NULL;
}
// check for missing newline character (line length too small)
if (xtni_line_cur[strlen(xtni_line_cur)-1] != '\n') {
printf("Line length too small \n");
printf("xtni_line_cur: %s\n", xtni_line_cur);
getchar();
return xtni_line_cur;
}
char * xtni_cur_word;
int xtni_num_words = 0;
xtni_cur_word = xtni_line_cur;
printf("xtni_line_cur: %s\n", xtni_line_cur); // testing
xtni_cur_word = strtok (xtni_cur_word," "); // first word
while (xtni_cur_word != NULL) {
strcpy(&xtni_words[xtni_num_words], xtni_cur_word);
xtni_cur_word = strtok (NULL," "); // next word
xtni_num_words++;
}
// check for max string length
if (strlen(xtni_words) > xtni_words_max) {
printf("xtni_words_max too low \n");
printf("xtni_words_max: %i\n", xtni_words_max);
printf("xtni_line_num: %i\n", xtni_line_num+1);
getchar();
return xtni_line_cur;
}
return xtni_line_cur;
}
int main()
{
xtni=fopen(XTNI_FILENAME, "r");
if (xtni == NULL) {
int errnum = errno;
printf ("%d\n", errnum); // Convert int to char
printf ("Error opening file. \n");
printf ("Error Number: %i\n", errnum);
printf ("File Name: %s\n", XTNI_FILENAME);
printf ("Error message: %s\n", strerror(errnum));
}
unsigned int xtni_words_max = 48;
char xtni_words[xtni_words_max];
int xtni_line_num = 0;
while (get_xtni(xtni_words_max, xtni_line_num, xtni_words) != NULL); {
printf("%s", &xtni_words[0]); // testing
xtni_line_num++;
}
return 0;
}
Comments? Suggestions?