You are on page 1of 2

//Writing to file

#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *f;

f = fopen("abc.txt","w");
if(f == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);
fprintf(f,"%d",num);
fclose(f);
return 0;
}

//Reading from file

#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *f;
if ((f = fopen("abc.txt","r")) == NULL){
printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(f,"%d", &num);
printf("Value of n=%d", num);
fclose(f);

return 0;
}

// Exception handling

#include <stdio.h>
#include <errno.h>

int main()
{

FILE * f;

f = fopen("cdf.txt", "r");

printf(" Value of errno: %d\n ", errno);


printf("The error message is : %s\n",
strerror(errno));
perror("Message from perror");
return 0;
}

// Error no. with messages

#include <stdio.h>
#include <errno.h>

int main()
{

int errno;

while(1)
{
printf(" Value of errno: ");
scanf("%d",&errno);

perror("Message from perror");


}

return 0;
}

You might also like