I want to know how to declare the exact size of storage in C , if I use array
or do the memory allocation such as malloc
, they all need to decide the size previously . In this situation , I will declare a very large size to prevent the overflow , but it still have probability to happened .
For example
If I want to split an text file to words , I need to declare a char **
to store the word string , but I can't know how much words will be split ?
If I want to read the file content into a array
I need to declare a large buffer to store
buffer = malloc(sizeof(char)*1000);
Any better or correct solutions? thanks
#include <stdio.h>
#include <stdlib.h>
void read_chars(char * file_name ,char * buffer);
int main(int argc ,char * argv[])
{
char * buffer ;
buffer = malloc(sizeof(char)*1000);
read_chars(argv[1],buffer);
printf("%s",buffer);
}
void read_chars(char * file_name ,char * buffer)
{
FILE * input_file ;
input_file = fopen(file_name,"r");
int i = 0;
char ch;
while((ch = fgetc(input_file)) != EOF)
{
*(buffer+i) = ch;
i++;
}
*(buffer+i) = '\0';
fclose(input_file);
}