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:

|