You try the following code
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 50
int main()
{
FILE *pFile = NULL;
char *filename = "test_write.txt";
char buffer[80] = "this is for testing ";//this is the data i am going to write into the file
int buffer_size = BUFFER_SIZE;
size_t str_length = 0;
pFile = fopen(filename, "w"); //opening the file for writing
if(pFile == NULL)//checking the error in open
{
printf("Error opening %s for writing. Program terminated.", filename);
abort();
}
str_length = strlen(buffer);
fwrite(buffer, str_length, 1, pFile); //writing the string to the file
fclose(pFile);
printf("\nFile write complete\n");
//reading that data from file
pFile = fopen("test_write.txt","r"); //opening the file for reading
if(pFile == NULL)
{
printf("Error opening %s for writing. Program terminated.", filename);
abort();
}
char data[1024];
memset(data,'\0',sizeof(data));//initializing with nulls o avoid buffer problems
fread(data,sizeof(char),34,pFile);//reading the data what i have written to file
fclose(pFile);
printf("%s\n",data);//this prints this is for testing
pFile = fopen(filename, "w"); //again opening for writing
if(pFile == NULL)
{
printf("Error opening %s for writing. Program terminated.", filename);
abort();
}
memset(data,'\0',sizeof(data)); //array is initialized with null
str_length = strlen(buffer);
fwrite(data, str_length, 1, pFile); //writing that null data
fclose(pFile);
printf("\nNull File write complete\n");
//reading that data from file
pFile = fopen("test_write.txt","r"); //now opening for reading the null data
if(pFile == NULL)
{
printf("Error opening %s for writing. Program terminated.", filename);
abort();
}
memset(data,'\0',sizeof(data));
fread(data,sizeof(char),34,pFile); //reading the data to the "data" buffer. Now it contains the null what we have written
fclose(pFile);
printf("%s\n",data); //this will print nothing because that is null
}