#include <stdio.h>
#include <stdlib.h>

char* filename = "textfile.txt";
char choice; //if you want to give the user the option to create the file
char userInput[1000];
char buffer[256];

FILE* fp;


void DisplayTextFileContentsOnScreen()
{
	fp = fopen(filename, "r");//read mode
	if (fp != NULL)
	{
		while (fgets(buffer, 256, fp))
		{
			printf("%s", buffer);
		}
	}
}

void AppendToTextFile(char value[])
{
	fp = fopen(filename, "a");//append
	fputs(value, fp);
}

void SaveAndCloseFile()
{
	fclose(fp);
}

void CreateTheTextFile()
{
	fp = fopen(filename, "w");//write mode, but it also works to create the text file
}


int main()
{
	fp = fopen(filename, "a");//append mode

	if (fp == NULL)
	{
		printf("File %s could not be opened", filename);
		
		//You need to create the text file first before writing your program
		//but in case you forgot to prepare the file, we can probably offer to write it here
		printf("\nShould we create a new file? [Y/N]: ");
		scanf("%c", &choice);
		if ((choice == 'y') || (choice == 'Y'))
		{
			CreateTheTextFile();
			AppendToTextFile("This is a sample text");
			SaveAndCloseFile();
			printf("\nFile generated and closed. Please restart this program");
		}
		return 0;
	}
	else //means file is accesed
	{
		printf("\nInput of the user: ");
		fgets(userInput, sizeof(userInput), stdin);//stores the user input to a variable

		//append the text of the file
		AppendToTextFile(userInput);
		SaveAndCloseFile();

		//display the text file contents?
		DisplayTextFileContentsOnScreen();
	}

	getch();

	return 0;
}
