C Language



Admission Enquiry Form

  

Write Integers into File in C File Handling




Write Data into File in C File Handling

Write Mode

This mode is used to open the file in write mode and this mode is denoted by ‘w’. This mode opens a new file on the disk for writing only. If the file already exists, the compiler will overwrite that file.
FILE *fptr; // declaration of file pointer
fptr= fopen(“FILE_NAME”,”w”); //opening a file in write mode only

Example to write two numbers into a file:

#include<stdio.h>
void main()
{
FILE *fptr;
int num1,num2;
fptr=fopen("compuhelp.txt","w");
printf("Enter first number ");
scanf("%d",&num1);
printf("Enter second number ");
scanf("%d",&num2);
if(fptr==NULL)
{
printf("\n File could not be opened ");
}
else
{
fprintf(fptr,"%d %d",num1,num2);
}
printf("\n Data saved into the file");
fclose(fptr);
}

Output:

Enter first number 100
Enter second number 200

Data saved into the file



Now you can see your notepad file named as compuhelp.txt into the hard-disk.It is saved into the default directory i.e. C:\COMPUHELP\c-notes