0

I have the following code:

int main(void)
{
    int lines_allocated = 128;
    int max_line_len = 100;
    int lines_allocated2 = 128;
    int max_line_len2 = 100;

    /* Allocate lines of text */
    char **words = (char **)malloc(sizeof(char*)*lines_allocated);
    if (words == NULL)
    {
        fprintf(stderr, "Out of memory (1).\n");
        exit(1);
    }

    FILE *fp = fopen("test1.txt", "r");
    if (fp == NULL)
    {
        fprintf(stderr, "Error opening file.\n");
        exit(2);
    }
    else
    {
        printf("Reading in test1.txt...\n");
    }

    int i;
    for (i = 0; 1; i++)
    {
        int j;

        /* Have we gone over our line allocation? */
        if (i >= lines_allocated)
        {
            int new_size;

            /* Double our allocation and re-allocate */
            new_size = lines_allocated * 2;
            words = (char **)realloc(words, sizeof(char*)*new_size);
            if (words == NULL)
            {
                fprintf(stderr, "Out of memory.\n");
                exit(3);
            }
            lines_allocated = new_size;
        }
        /* Allocate space for the next line */
        words[i] = malloc(max_line_len);
        if (words[i] == NULL)
        {
            fprintf(stderr, "Out of memory (3).\n");
            exit(4);
        }
        if (fgets(words[i], max_line_len - 1, fp) == NULL)
            break;

        /* Get rid of CR or LF at end of line */
        for (j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || words[i][j] == '\r'); j--)
            ;
        words[i][j] = '\0';
    }

    int j;
    for (j = 0; j < i; j++)
    {
        printf("%s\n", words[j]);
    }
    return 0;
}

I'm trying to read in a file and store each line in the words array. My input file contains:

1 345363

0 149378

0 234461

0 454578

However, the last number on each line gets cut off. So the first index will print 34536 when it should print out 345363. I can't seem to figure out whats wrong.

Tim
  • 41,901
  • 18
  • 127
  • 145
user3610554
  • 23
  • 1
  • 5

2 Answers2

0

The problem is in the line

for (j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || words[i][j] == '\r'); j--)

change j = strlen(words[i]) - 1; to j = strlen(words[i]); it will print the output properly...

0

To get rid of CR or LF at end of line, try this:

char *cp;

while((cp=strchr(words[i], '\r')))
   *cp='\0';

while((cp=strchr(words[i], '\n'))(
   *cp='\0';

Instead of this:

for(j = strlen(words[i]) - 1; j >= 0 && (words[i][j] == '\n' || words[i][j] == '\r'); j--)
      ;
words[i][j] = '\0';
Mahonri Moriancumer
  • 5,993
  • 2
  • 18
  • 28