Number of characters in a file?

2.7k Views Asked by At

I would like to know if there is a method for reading characters from a file and saving them into an array without a specified array length.

In normal situation I read all the characters and count them. (step 1) Then I create the array with malloc and read the characters from the file, so I am forced to read the whole file twice. Can it be done with only one reading?

3

There are 3 best solutions below

7
On BEST ANSWER

The normal way to do this is to do a fseek to end of file, then you are not actually reading all the characters twice.

fseek( fp, 0L, SEEK_END );
size_t size = ftell(fp);
fseek( fp, 0L, SEEK_SET );
char* buffer = malloc( size );
fread( buffer, 1, size, fp );
0
On

The above solutions are quite right. But I want to add that we should open the file "rb" that is binary mode to make them work. If you open the file with simple "r"/"a", then the file will get opened in text mode. fseek and ftell method gives us byte length of the entire file. If you are working with binary data (do not use fscanf/fprintf) , i.e. using fread and fwrite, then it suits you best. I am not sure if that will work if you use fscanf/fprintf/fgets For example

#include<stdio.h>
int main() {
  FILE *fid;
  char *data;
  long int size;
  fid = fopen("filename", "rb");
  fseek(fid, 0l, SEEK_END);
  size = ftell(fid);
  data = (char *) malloc(size);
  fseek(fid, 0l, 0);

  data = fread(data, 1, size, fid);
  // Use the data !!
}
3
On

You can find the number of characters in the file by finding the size of the file.

int size = 0;
char* aFileContents = NULL;

fseek(fp, 0L, SEEK_END);
size = ftell(fp);
fseek(fp, 0L, SEEK_SET);  // reset the file pointer

aFileContents = (char*)malloc(size);

//  use the data

free(aFileContents);