LearningCODE
LearningCODE

Reputation: 165

How to make a char array from a file?

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

int count_arr(FILE *file)
{
 int c,count=0;
//FILE *file;
//file = fopen("test.txt", "r");
if (file) {
    while ((c = getc(file)) != EOF){
        putchar(c);
        ++count;}
    fclose(file);
}
return count;
}

void make_arr (FILE *file, char arr[]){
     int c,n=0,count=0;
     char ch;
//FILE *file;
//file = fopen("test.txt", "r");
if (file) {
    while ((c = getc(file)) != EOF){
    ch = (char)c;
    arr[n]=ch;
    ++n; }
    fclose(file);
}

}


int main(){
FILE *file;
int n;
//scanf("%c",&file_name);
file = fopen("test.txt","r");

int count = count_arr(file);
char arr [count];

make_arr(file, arr);

for(n=0; n<count;++n) printf("%c",arr[n]);

}

So far this is all I have for my code. I know I am doing it completely wrong. When I print out the char array it prints random junk... I am trying to code a function "make_arr" that passes an array which gets stored with characters from a file. Any help would be appreciated!

Upvotes: 1

Views: 3229

Answers (1)

Cyclonecode
Cyclonecode

Reputation: 30001

Here is an small example that reads a file into a buffer:

FILE* file = fopen("file.txt", "r");
// get filesize
fseek(file, 0, SEEK_END);
int fsize = ftell(file);
fseek(file, 0, SEEK_SET);
// allocate buffer **note** that if you like
// to use the buffer as a c-string then you must also
// allocate space for the terminating null character
char* buffer = malloc(fsize);
// read the file into buffer
fread(buffer, fsize, 1, file);
// close the file
fclose(file);

 // output data here
for(int i = 0; i < fsize; i++) {
   printf("%c", buffer[i]);
}

// free your buffer
free(buffer);

If you really would like to use a function to fill your buffer this would work (not really see the point though), although I still will make only one read operation:

void make_array(FILE* file, char* array, int size) {
   // read entire file into array
   fread(array, size, 1, file);
}

int main(int argc,char** argv) {
  // open file and get file size by first
  // moving the filepointer to the end of the file
  // and then using ftell() to tell its position ie the filesize
  // then move the filepointer back to the beginning of the file
  FILE* file = fopen("test.txt", "r");
  fseek(file, 0, SEEK_END);
  int fs = ftell(file);
  fseek(file, 0, SEEK_SET);
  char array[fs];
  // fill array with content from file
  make_array(file, array, fs);
  // close file handle
  fclose(file);

  // output contents of array
  for(int i = 0; i < fs; i++) {
    printf("%c\n", array[i]);
  }
  return 0;
}

Like I stated in the comments above you need to add space for the terminating null character if you like to use the char array as a string:

char* array = malloc(fs + 1);
fread(array, fs, 1, file);
// add terminating null character
array[fs] = '\0';
// print the string
printf("%s\n", array);

Upvotes: 2

Related Questions