Skip to content

Instantly share code, notes, and snippets.

@sojohnnysaid
Created September 13, 2018 19:20
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
simple way to create a new file in c
#include <stdio.h>
int main(void){
// write a program that creates a simple txt file
// create a FILE pointer data type fp
// this is a new file we are creating
FILE * fp;
// we have to fopen the file and choose what mode we
// want to be in, which in this case is "w" for write
// fopen returns a FILE pointer data type which is what
// we need to do actions like write or read etc
// This file doesn't exist yet so this variable is just
// an empty bucket until we fill it with data using fwrite
fp = fopen("mynewfile.txt", "w");
// we'll have some data we want in the file within an array
char data[] = "nice\n";
// this is an array ['n','i','c','e'];
// we'll invoke the fwrite function and pass it
// the data (array), the size of each element,
// the total number of elements and the pointer to the file.
// In our case
// we will use sizeof(array) because we are
// going to write every char within our array (a string)
fwrite(data, sizeof(data[0]), sizeof(data), fp);
fclose(fp);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment