0

I have a program that will open a text file and read line by line. It also puts each line into an array. When I use this function and try to use each line in a printf statement, new line characters are added.

My code:

    char fileContents[MAX_LINES][MAX_LINE_LENGTH];
    int lineCount = 0;

    FILE *ifp = fopen("Tree-B.txt", "r");
    if (ifp == NULL)
    {
        printf("Error opening file!\n");
        exit(1);
    }

    while (fgets(fileContents[lineCount++], MAX_LINE_LENGTH, ifp) != NULL);
    fclose(ifp);

    printf("Name: %s is now %s", fileContents[0], fileContents[1]);

The output of this is as follows:

Name: Tree Bacon
 is now 30.21

The printf is adding new line characters and I can't seem to discover why this is happening.

The two lines that were read from my text file were:

Tree Bacon
30.21
meetar
  • 7,443
  • 8
  • 42
  • 73

2 Answers2

0

Because fgets also stores the trailing newline, you can remove it using strchr:

char *ptr;

while (fgets(fileContents[lineCount], MAX_LINE_LENGTH, ifp) != NULL) {
    ptr = strchr(fileContents[lineCount], '\n');
    if (ptr != NULL) {
        *ptr = '\0';
    }
    linecount++;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
0

My favourite way to remove that trailing newline read by fgets is with strcspn

while (fgets(fileContents[lineCount], MAX_LINE_LENGTH, ifp) != NULL) {
    fileContents[lineCount] [ strcspn(fileContents[lineCount], "\r\n") ] = 0;
    linecount++;
}

Of course, you must defer incrementing the array index.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56