0

I am trying to apply dynamic memory allocation on reading text files but I don't really get how I could access the contents of the file. I am still having difficulties understanding memory allocation so if it is possible, please explain how I can apply it on file handling.

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


int main(void) {
    int counter = 0;
    char ch;
    char **chpt;
    FILE *fp;

    fp = fopen("test.txt", "r");

    while((ch = fgetc(fp)) != EOF ){
        counter++;
    }
    rewind(fp);

    chpt = (char **)malloc(counter * sizeof(char));

    fread(chpt, counter * sizeof(char), 1, fp);

    for (int i = 0; i < counter; i++){
        for (int j = 0; j < counter; j++) {
            printf("%c", chpt[i][j]);
        }
    }

    fclose(fp);
    free(chpt);
    return 0;
}


Nick
  • 9
  • 5

1 Answers1

0

Your nested for loops don't make any sense and you're trying to print counter*counter characters, but you have only read counter characters. You don't have a 2D array here, and you don't need one either.

Furthermore:

  • you need to check if fopen fails
  • the cast with malloc is not needed (but it doesn't harm either)

Your file contains obviously counter characters. So you need to allocate memory for counter characters, read counter characters from the file, and then display the counter characters you've just read.

You want this:

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

int main(void) {
  int counter = 0;
  char ch;
  char* chpt;      // just a pointer to char
  FILE* fp;

  fp = fopen("test.txt", "r");
  if (f == NULL)                 // check if fopen failed
  {
    printf("Can't open file\n");   // print error message
    return 1;                    // and abort
  }

  while ((ch = fgetc(fp)) != EOF) {
    counter++;
  }
  rewind(fp);

  chpt = malloc(counter * sizeof(char));  // no cast needed

  fread(chpt, counter * sizeof(char), 1, fp);

  for (int i = 0; i < counter; i++) {     // one loop is enough
      printf("%c", chpt[i]);
  }

  fclose(fp);
  free(chpt);
  return 0;
}

There is still room for further improvement:

  • you should check if malloc fails, even if it's unlikely to fail if the file isn't huge
  • your method of determining the file size is very inefficient, for more information read this
  • sizeof(char) is not needed, it is 1 by definition.
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
  • Thank you for the advice! and wow... I have really grossly misunderstood pointers and addresses.... but I totally get what you are saying now I'll make sure to read more..... – Nick Feb 16 '22 at 14:38