Question

I'm wondering if I could get some assistance in figuring out how to read in text from a file into an array in C. My main goal is to make a text formatter that will right justify the text, but for right now I'm just trying to properly read in the text.

Thanks in advance!

#include<stdlib.h>
#include<stdio.h>
#define TEMP 1000
int main() {

  int words_in_line = 0;
  int spaces_to_put = 0;
  int z; //for loop
  int i; //for loop
  int count; //indicates when to put a new line.
  int k; //for loop
  int w; //for loop
  int drop_spaces; //for loop
  int check;
  size_t nread;
  FILE *f_open;
  char buffer[TEMP];

  f_open = fopen("hollow.txt", "r");
  char *buf = malloc(TEMP);

  printf("Enter the length of chars in a line: \n");
  scanf("%d", &w);

  if (buf == NULL) {
    printf("Buf is null \n");
  }

  while ((nread = fread(buf, 1, TEMP, f_open)) > 0) { //going through the stream.
    buffer[TEMP] = fwrite(buf, 1, nread, stdout); //need to load the steam into the array.
    //size_t cannot match char[].
  }
  if (ferror(f_open)) {
    printf("Error reading file \n");
  }
  return 0;
}
Was it helpful?

Solution

Rather than use fread()/fwrite() to read in text, use fgets() to read and fprintf() to justify.

assert(w >= 0);
while (fgets(buf, TEMP, f_open) != NULL) {
  // right justify the text
  fprintf(stdout, "%*s", w + 1, buf);
}

The + 1 is for the usual \n at the end of buf. A bit more work is needed to deal with the case when \n is not there. e.g. last line of a file.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top