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 )
- buffer - pointer to the first object in the array to be written
- size - size of each object
- count - the number of the objects to be written
- stream - pointer to the output 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 :
- to make an array of character and write to its elements
- make that array bigger and bigger using
malloc
andrealloc
- Writing continues until it reach the
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;
}