Writing strings to a file
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 50
int main()
{
FILE *pFile = NULL;
char *filename = "C:\\myfile.txt";
char buffer[80] = "asdf";
int buffer_size = BUFFER_SIZE;
size_t str_length = 0;
pFile = fopen(filename, "w");
if(pFile == NULL)
{
printf("Error opening %s for writing. Program terminated.", filename);
abort();
}
str_length = strlen(buffer);
fwrite(&str_length, sizeof(size_t), 1, pFile);
fwrite(buffer, str_length, 1, pFile);
fclose(pFile);
printf("\nFile write complete\n");
if(buffer != NULL)
free(buffer);
}
Related examples in the same category