Home > database >  store data in an array using getc()
store data in an array using getc()

Time:11-08

is there any way to store data in an array from a file using getc() function, not fscanf()?

For example, there is a file "file.txt" containing following data:

Name
Surname
Age

So the content of the array arr[] would be:

arr[] = {Name, Surname, Age}

So far I could only print out the content of the file to the console:

#include <stdio.h>

int main(void)
{
    setvbuf(stdout, NULL, _IONBF, 0);
    FILE *file = fopen("file.txt", "r");
    int ch;
    while (((ch = getc(file)) != EOF) )
    {
        putc(ch, stdout);
    }
    return 0;
}

It was a requirement of the assignment that libraries other than stdio.h cannot be used. I can easily do it with fscanf() but getc() function creates some not some difficulties.

CodePudding user response:

is there any way to store data in an array from a file using getc() function, not fscanf()?

Yes. By reading and assigning values to an element of an array, and increasing the index for each character. Repeat this until a newline character is found, or the file is exhausted.

Make sure to leave room for the null-terminating byte (\0') in order to create a string, by placing one after the last character read.

A quick alteration to your example:

#include <stdio.h>

#define FILENAME "file.txt"
#define MAXSIZE 128

int main(void)
{
    setvbuf(stdout, NULL, _IONBF, 0);
    FILE *file = fopen(FILENAME, "r");
    
    if (!file) {
        perror(FILENAME);
        return 1;
    }

    int ch;
    size_t i = 0;
    char array[MAXSIZE];

    while (i < MAXSIZE - 1 && ((ch = getc(file)) != EOF)) {
        if (ch == '\n')
            break;

        array[i  ] = ch;
    }

    /* null-terminate the array to create a string */
    array[i] = '\0';

    fclose(file);

    puts(array);
}

If you extract this logic into its own function, that accepts an array to fill, a character limit, and the file to read from, and you will have largely recreated fgets.

  • Related