I want to write sentence(s) to a text file using fwrite
function. So I have to have these as function arguments:
fwrite( const void *restrict buffer, size_t size, size_t count, FILE *restrict stream )
As the How to dynamically allocate memory space for a string and get that string from user? said, it is a bad practice to waste memory. I read the answer and got an idea to write a code in my way.
My idea is :
malloc
and realloc
EOF
Unfortunately I encounter a problem. Whenever I build and execute the code it gives me this error:
has stopped working
Heres my code:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
size_t index=0,size=1;
char ch;
FILE *fptr;
fptr=fopen("E:\\Textsample.txt","w");
/////////////////Checking///////////////
if(fptr==NULL)
{
free(fptr);
puts("Error occured!\n");
exit(EXIT_FAILURE);
}
/////////////////Checking///////////////
char *sentence =(char*) malloc(sizeof(char)) ;
puts("Plaese write :\n");
while((ch=getchar()) != EOF)
{
sentence[index]=ch;
index++;
size++;
realloc(sentence,size);
/////////////////Checking///////////////
if(sentence==NULL)
{
printf("Error Occured!\n");
free(sentence);
exit(EXIT_FAILURE);
}
/////////////////Checking///////////////
}
//Copying sentnce(s) to the text file.
fwrite(sentence,sizeof sentence[0],index,fptr);
free(sentence);
free(fptr);
return 0;
}
You need to write sentence = realloc(sentence, size)
, I think.
Also , it's more efficient to double the alloc-ed size, every time we need to.
Then we can read as many again as we have read already, so we need fewer reallocations. So then size
doubles (it is the size of the allocated buffer, while index
keeps track of read characters.
So
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
size_t index=0,size=1;
int ch;
FILE *fptr;
fptr=fopen("./bla.txt","w");
/////////////////Checking///////////////
if(fptr==NULL)
{
fprintf(stderr, "Error occured!\n");
exit(EXIT_FAILURE);
}
/////////////////Checking///////////////
char *sentence = malloc(size) ;
puts("Please write, (close with return) :\n");
while((ch=getchar()) != '\n')
{
sentence[index]=(ch & 0xff);
index++;;
if (index >= size){
sentence = realloc(sentence,2*size);
/////////////////Checking///////////////
if(sentence==NULL)
{
fclose(fptr);
fprintf(stderr, "Error Occured!\n");
free(sentence);
exit(EXIT_FAILURE);
}
/////////////////Checking///////////////
size *= 2; /* update size */
}
}
//Copying sentence(s) to the text file.
fwrite(sentence,1,index,fptr);
free(sentence);
fclose(fptr);
return 0;
}
which works fine on my system.