Online Hibernate Training just in Rs. 1000

One week online training in Hibernate ORM framework. Learn Hibernate Framework and enhance your skills. Best Online Hibernate training at 90% discount. Join Now!! Offer is valid Only for limited Period!!! Online Training

C file write example

Here we are using the library function fwrite() to write the data into the file.

Ads

C file write example

     

This section demonstrates you to write the data into the file.

Here we are using the library function fwrite() to write the data into the file. You can see in the given example, we have stored the string into the buffer which is to be written into the specified file 'Hello.txt'. The type FILE stores all the information related to file stream. The function fopen(file, "w") opens the file and allow to perform write operations into the file. The library function strlen() provided by the header file <string.h> determines the length of the string which is stored into buffer. The function fwrite(buffer, len, 1, p) write the buffer value into the file and fclose() function closes the file stream and flushes the buffer.

Here is the code:

FILEWRIT.C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void main() {
  FILE *p = NULL;
  char *file = "C:\\Hello.txt";
  char buffer[80"Don't look for endings when you need a beginning.";
  size_t len = 0;
  p = fopen(file, "w");
  if (p== NULL) {
  printf("Error in opening a file..", file);
  }
  len = strlen(buffer);
  fwrite(buffer, len, 1, p);
  fclose(p);
  printf("\nWritten Successfuly in the file.\n");
  if (buffer != NULL)
  free(buffer);
  getch();
}

When you run the above example, the string will get stored into the file and shows the message:

Download Source Code:

Advertisements

Ads
Share on Google+Share on Google+

C file write example

Posted on: February 5, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: C file write example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:2
Russcat
June 4, 2011
free call

You shouldn't be freeing buffer - it's on the stack not allocated using malloc or calloc.
Russcat
June 4, 2011
NULL check

Your code shouldn't try to write to a NULL pointer after detecting it.

Ads

 

Ads