File Output (Writing) - 1. Writing a block of data to a file.What we will learn: How to create a file, and print something simple into it using fwrite.
Ok, so once again we open up our favourite text editor and create our main.c file. Once you have done that, we need some includes!
#include <stdio.h>
#include <stdlib.h>
I have already explained these includes! We may not need stdlib, but meh

So know we start our main function:
int main(void) {
Next we declare some variables.
FILE * pFile;
char buffer[] = "Humpty Dumpty sat on the wall";
Here we are saying pFile is a file pointer and buffer contains chars, we can also say what chars it contains, eg. "char foo[] = "blah".
Next we need to open our file...
pFile = fopen ("myfile.txt" , "w");
As you can see, we are opening the file for writing insted of for reading!
w, "Create an empty file for writing. If a file with the same name already exists its content is erased".
Next we use a shiny new function! ooOOoo...

fwrite (buffer , 1 , 29 , pFile);
fwrite, "Write a block of data to a stream". This function requires 4 parameters: buffer, size, count and stream
buffer, this coincidently is the first parameter, the "buffer". This is the pointer to the data to be written. So whatever is in "buffer" is going to be writen to the file.
1, This is th second parameter, the "size". "Size in bytes of each item that has to be written".
29, This is the penultimate parameter. the "count". "Number of items, each one with a size of size bytes". This is how many bytes from the buffer do you want to write to the file. In this case, we want all of it and the buffer is 29 bytes.
pFile, This is the final parameter, the "stream". "pointer to an open file
with writing access". As you can see i made "with writing access" bold, this is to show that the file
must of been opened with writing access.
So, now we have had a new function, what now?!
The same as normal, we just close the file and return 0 to show that all went well.
fclose (pFile);
return 0;
Close the main function:
}
Here is what your code should look like:
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE * pFile;
char buffer[] = "Humpty Dumpty sat on the wall";
pFile = fopen ("myfile.txt" , "w");
fwrite (buffer , 1 , 29 , pFile);
fclose (pFile);
return 0;
}
Now, compile this with your compiler (gcc!) and execute the output binary, you should be left with a file called "myfile.txt" which inside says: "Humpty Dumpty sat on the wall".
Yes, its as simple as that, simpler than reading a file actually!
Congratulations! You just wrote to a file in C!
--harleyg