CS Beginner
CS Beginner

Reputation: 43

C - Reading from a .txt file and storing the characters inside an array

I have a .txt file called 'exampleWheel.txt' which contains 10 characters: A,M,W,O,S,E,G,L,P,H.

enter image description here

I am trying to store the characters inside an array so that I can reference to each character later according to its position in the array.

Here is my attempt:

#include <stdlib.h>

int main()
{
    FILE * fPointer;
    fPointer = fopen("exampleWheel.txt","r");
    int i = 0;

    char singleLine[150];
    const char *array[10];

    while(!feof(fPointer)){
        fgets(singleLine, 150, fPointer);
        array[i] = singleLine;
        printf("%d\n",&array[i]);
        printf("%s\n", array[i]);
        i++;
    }
    fclose(fPointer);

    printf("array[0] = %c\n", array[0]);
    printf("array[1] = %c\n", array[1]);
    return 0;
}

The printf statements in the while loop return the correct output but the two printf outside the while loop returns the wrong results.

i.e printf("array[0] = %c\n", array[0]) does not return the first character of the array

Please show me how to improve my code. Thank you in advance!!

Upvotes: 0

Views: 74

Answers (1)

Stephan Schlecht
Stephan Schlecht

Reputation: 27126

  • when opening a file you should always check for errors and handle them e.g. inform the user and end the program with an error code
  • try to read from a file and don't check upfront with feof, please read Why is “while ( !feof (file) )” always wrong?
  • the assignment array[i] = singleLine; stores a pointer to the singleLine character array, but it will be overwritten with the next fgets call in the loop. As an alternative you could use e.g. a two-dimensional array here and simply save the first character.
  • you should make sure to not read more lines then you have space for in array, otherwise you write over then end of the array

You slightly modified code could look like this then:

#include <stdlib.h>
#include <stdio.h>


#define MAX_LINES 10

int main() {
    char singleLine[150];
    char array[MAX_LINES][2];

    FILE *fPointer;
    if ((fPointer = fopen("exampleWheel.txt", "r")) == NULL) {
        fprintf(stderr, "can't open file");
        exit(1);
    }
    int i = 0;
    while (i < MAX_LINES && fgets(singleLine, 150, fPointer)) {
        array[i][0] = singleLine[0];
        array[i][1] = '\0';
        printf("%d\n", *array[i]);
        printf("%s\n", array[i]);
        i++;
    }
    fclose(fPointer);

    printf("array[0] = %c\n", array[0][0]);
    printf("array[1] = %c\n", array[1][0]);
    return 0;
}

Upvotes: 1

Related Questions