Write Data To Text File In C: Character by Character

Advertisement:

This video tutorial demonstrates the creation of a simple file and writing data to text file ‘character by character’ using a simple C program.

  #include< stdio.h>

is the only header file required to include.

DOSBOX
I’m using a software called DOSBOX to write my c program. Using this software we can run 32-bit programs on our 62-bit machine.
I’m mounting my C:/DOSFOLDER here. So C:/DOSFOLDER will be treated as my C drive.

Here is the DOS code to do that:

z:\> mount c "c:/DOSFOLDER"
z:\>c:
c:\>cd TC
c\TC:>tc

We take a pointer variable of FILE type, so that this variable can be used to further reference to the file.

FILE *p;
char ch;

ch is a char type variable to store user entered characters and to transfer it to the file.

  p = fopen("c:\\Hello.txt","w");

fopen function takes two parameters. First one being the path of the file(if the file doesn’t exist, it creates one by itself), second parameter indicates the write mode. i.e., the file is opened in write mode and is intended for the write operation.

Note: If you are using DOSBOX software, then the file will be created at this location c:/DOSFOLDER/Hello.txt

       clrscr();
 
        printf("\nEnter the text nd hit Enter to Terminate\n");

clrscr() clears the screen and the print statement asks the user to enter some text and hit enter to terminate.

while( (ch=getche()) !='\r' )
	fputc( ch,p);

getche() is a function that gets a character from the keyboard, echoes to screen.
These characters are stored in char variable ch. If the entered character is not “Enter Key” that is \r charriage return character, then the control enters the while loop and using fputc function it transfers the content(character) present in ch to p(variable which references the file we have opened for writing).

fclose(p);

closes the file, opened for write operation.

Video Tutorial: Creating and Writing Data To A Simple File: in C


You need to a flashplayer enabled browser to view this YouTube video

YouTube Link: http://www.youtube.com/watch?v=4V1qAw-XImI [Watch the Video In Full Screen.]



Full Source code to Creating and Writing Data To A Simple File: in C

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include< stdio.h> /* no space b/w < and stdio.h */
 
void main()
{
	FILE *p;
	char ch;
 
	p = fopen("c:\Hello.txt","w");
	clrscr();
 
	printf("\nEnter the text nd hit Enter to Terminate\n");
 
	while( (ch = getche()) != '\r' )
	 fputc( ch, p );
 
	fclose(p);
}

Output:
Recruitment’s in C.

Advertisements

1 thought on “Write Data To Text File In C: Character by Character”

Leave a Reply

Your email address will not be published. Required fields are marked *