1

Here is my code so far. My array just isn't being populated. The problem is happening with fscanf. I know it reads in the characters just fine because I've tried reading them into a generic char pointer / string and it reads just fine. Just not sure how to copy the chars into the complicated array. Pointer to a pointer :O Text file format might something like..

Alice
Bob
Jerry
Ted

My code:

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

int main()
{
    int lineCount = 1;
    char* fileInput;
    char c[100];

    int allocatedBytes = 0;

    fileInput = (char*)malloc(100*sizeof(char));
    printf("File name: ");
    gets(fileInput);

    FILE * fptr;

    if ((fptr = fopen(fileInput, "r")) == NULL)
    {
        printf("Error! opening file");
        // Program exits if file pointer returns NULL.
        exit(1);
    }

    //get number of names before dynamic array allocation
    for(char c = getc(fptr); c!= EOF; c=getc(fptr))
        if(c == '\n')
            lineCount = lineCount + 1;

    char **names = malloc(lineCount * sizeof(char *));

    for(int i=0; i<lineCount; i++)
        names[i] = (char *)malloc(100);

    int i=0;
    while((fscanf(fptr, "%99s", names[i]))!=EOF)
        i++;

    for(int i=0; i<lineCount; i++)
        printf("%s\n", names[i]);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
kelemeno
  • 53
  • 5
  • 3
    You read through the file when you count lines. You need to rewind the file pointer to then read the data. – 001 Sep 22 '19 at 17:33
  • [The `gets()` function is too dangerous to be used — ever!](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used) Also, it is a good idea to report error message on standard error (`stderr`) rather than standard output (`stdout`). And, when reporting that you failed to open a file, it is a good idea to include the file name — it helps people check whether they made a typo, for example. Including error information (via `errno` and `` and `strerror()` from ``) is often a good idea. – Jonathan Leffler Sep 22 '19 at 18:25

1 Answers1

0

The file pointer(fptr) used in fgetc is reused for fscanf also. fget might have changed File pointer (fptr ) structure value like reading position and writing position. Try using another file pointer for fscanf. In this code getc is used instead of fgetc.So, ensure this also.