Home C-tutorials C file write example



C file write example
Posted on: February 5, 2009 at 12:00 AM
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:

Related Tags for C file write example:
cstringlibraryfiledatafunctionfuniobufferusingintwriteiftxtieexampleunctoexamstorecieilitlibcanlipeinrarfwritemnttrcaspecfuncintostoredtorxawhichxampsspeeatishellohallivmplarstrxtwrittenufttssriringthavsthellofepleplono


More Tutorials from this section

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

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.