Home C-tutorials C file write example
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

C file write example

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

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:

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 5, 2009

Ask Questions?    Discuss: C file write example   View All Comments

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
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.
DMCA.com