Skip to main content

Writing Data Into A File using C.

Writing Data Into A File


We can write data into a file. The following is the algorithm for writing data:
Create a file using fopen() function
Write data into a file using fprintf() and fputs() functions
Close a file using fclose() function
For testing, we create data into a file, demo.txt. For implementation, create a file, called
filewrite.c, and write this code.



#include <stdio.h>
int main(int argc, const char* argv[]) {
int i;
FILE *f;


f = fopen("demo.txt", "w+");

 
for(i=0;i<5;i++){
   fprintf(f, "fprintf message %d\n",i);
   fputs("fputs message\n", f);
// no format
}


fclose(f);
printf("Data was written into a file\n");


return 0;
}

Save this code. Compile and run this program.


 

Comments

Popular posts from this blog

Convert numbers to roman numerals

Convert numbers to roman numerals       #include <stdio.h> #include <conio.h> void predigits (char c1,char c2); void postdigits (char c,int n); char roman_Number[1000]; int i=0; int main() {     int j;     long int number;        printf( "Enter any natural number: " );     scanf( "%d" ,&number);        if (number <= 0) {          printf("Invalid number");          return 0;     }     while (number != 0){          if (number >= 1000){              postdigits('M',number/1000);              number = number - (number/1000) * 1000;          } ...

Sum, Average and Standard deviation in c

 Sum, Average and Standard deviation Write a function that receives 5 integers and returns the sum, average and standard deviation of these numbers. Call this function from main( ) and print the results in main( ). #include <stdio.h> void stat(int a,int b,int c,int d,int e,int *su,float *av,float *std) void main() { clrscr(); float ave,sd; int a,b,c,d,e,sum; printf( "\nInput 5 integers\n" ); scanf( "\n%d\n%d\n%d\n%d\n%d" ,&a,&b,&c,&d,&e);   stat(a,b,c,d,e,&sum,&ave,&sd); printf( "\nThe sum is %d\nThe average is %f\nThe standard deviation is %f" ,sum,ave,sd); } void stat(int a,int b,int c,int d,int e,int *su,float *av,float *std) { * su=a+b+c+d+e; * av= * su/5; * std=sqrt(((((a-*av)*(a-*av))+((b-*av)*(b-*av))+((c-*av)*(c-*av)))/5.0); }

To Create Triangle and Structure

 To Create Triangle and Structure   C Program To display the triangle using *, numbers and character Write a C Program to print half pyramid as using * as shown in figure below. * * * * * * * * * * * * * * * #include <stdio.h> int main () { int i , j , rows ; printf ( "Enter the number of rows: " ); scanf ( "%d" ,& rows ); for ( i = 1 ; i <= rows ; ++ i ) { for ( j = 1 ; j <= i ; ++ j ) { printf ( "* " ); } printf ( "\n" ); } return 0 ; }     Write a C Program to print half pyramid as using numbers as shown in figure below. 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5   #include <stdio.h> int main () { int i , j , rows ; printf ( "Enter the number of rows: " ); scanf ( "%d" ,& rows ); for ( i = 1 ; i <= rows ; ++ i ) { for ( j = 1 ...