C and C++ Programming Resources

Custom Search

File Handling in C Language

In this section, we will discuss about files which are very important for storing information permanently. We store information in files for many purposes, like data processing by our programs.

What is a File?

Abstractly, a file is a collection of bytes stored on a secondary storage device, which is generally a disk of some kind. The collection of bytes may be interpreted, for example, as characters, words, lines, paragraphs and pages from a textual document; fields and records belonging to a database; or pixels from a graphical image. The meaning attached to a particular file is determined entirely by the data structures and operations used by a program to process the file. It is conceivable (and it sometimes happens) that a graphics file will be read and displayed by a program designed to process textual data. The result is that no meaningful output occurs (probably) and this is to be expected. A file is simply a machine decipherable storage media where programs and data are stored for machine usage.

Essentially there are two kinds of files that programmers deal with text files and binary files. These two classes of files will be discussed in the following sections.

ASCII Text files

A text file can be a stream of characters that a computer can process sequentially. It is not only processed sequentially but only in forward direction. For this reason a text file is usually opened for only one kind of operation (reading, writing, or appending) at any given time.

Similarly, since text files only process characters, they can only read or write data one character at a time. (In C Programming Language, Functions are provided that deal with lines of text, but these still essentially process data one character at a time.) A text stream in C is a special kind of file. Depending on the requirements of the operating system, newline characters may be converted to or from carriage-return/linefeed combinations depending on whether data is being written to, or read from, the file. Other character conversions may also occur to satisfy the storage requirements of the operating system. These translations occur transparently and they occur because the programmer has signalled the intention to process a text file.

Binary files

A binary file is no different to a text file. It is a collection of bytes. In C Programming Language a byte and a character are equivalent. Hence a binary file is also referred to as a character stream, but there are two essential differences.

  1. No special processing of the data occurs and each byte of data is transferred to or from the disk unprocessed.
  2. C Programming Language places no constructs on the file, and it may be read from, or written to, in any manner chosen by the programmer.

Binary files can be either processed sequentially or, depending on the needs of the application, they can be processed using random access techniques. In C Programming Language, processing a file using random access techniques involves moving the current file position to an appropriate place in the file before reading or writing data. This indicates a second characteristic of binary files.
They a generally processed using read and write operations simultaneously.

For example, a database file will be created and processed as a binary file. A record update operation will involve locating the appropriate record, reading the record into memory, modifying it in some way, and finally writing the record back to disk at its appropriate location in the file. These kinds of operations are common to many binary files, but are rarely found in applications that process text files.

Creating a file and output some data

In order to create files we have to learn about File I/O i.e. how to write data into a file and how to read data from a file. We will start this section with an example of writing data to a file. We begin as before with the include statement for stdio.h, then define some variables for use in the example including a rather strange looking new type.

/* Program to create a file and write some data the file */
#include <stdio.h>
#include <stdio.h>
main( )
{
     FILE *fp;
     char stuff[25];
     int index;
     fp = fopen("TENLINES.TXT","w"); /* open for writing */
     strcpy(stuff,"This is an example line.");
     for (index = 1; index <= 10; index++)
     	fprintf(fp,"%s Line number %d\n", stuff, index);
     fclose(fp); /* close the file before ending program */
}

The type FILE is used for a file variable and is defined in the stdio.h file. It is used to define a file pointer for use in file operations. Before we can write to a file, we must open it. What this really means is that we must tell the system that we want to write to a file and what the file name is. We do this with the fopen() function illustrated in the first line of the program. The file pointer, fp in our case, points to the file and two arguments are required in the parentheses, the file name first, followed by the file type.

The file name is any valid DOS file name, and can be expressed in upper or lower case letters, or even mixed if you so desire. It is enclosed in double quotes. For this example we have chosen the name TENLINES.TXT. This file should not exist on your disk at this time. If you have a file with this name, you should change its name or move it because when we execute this program, its contents will be erased. If you don’t have a file by this name, that is good because we will create one and put some data into it. You are permitted to include a directory with the file name.The directory must, of course, be a valid directory otherwise an error will occur. Also, because of the way C handles literal strings, the directory separation character ‘\’ must be written twice. For example, if the file is to be stored in the \PROJECTS sub directory then the file name should be entered as “\\PROJECTS\\TENLINES.TXT”. The second parameter is the file attribute and can be any of three letters, r, w, or a, and must be lower case.

Reading (r)

When an r is used, the file is opened for reading, a w is used to indicate a file to be used for writing, and an a indicates that you desire to append additional data to the data already in an existing file. Most C compilers have other file attributes available; check your Reference Manual for details. Using the r indicates that the file is assumed to be a text file. Opening a file for reading requires that the file already exist. If it does not exist, the file pointer will be set to NULL and can be checked by the program.

Here is a small program that reads a file and display its contents on screen.

/* Program to display the contents of a file on screen */
#include <stdio.h>
void main()
{
   FILE *fopen(), *fp;
   int c;
   fp = fopen("prog.c","r");
   c = getc(fp) ;
   while (c!= EOF)
   {
   		putchar(c);
		c = getc(fp);
   }
   fclose(fp);
}

Writing (w)

When a file is opened for writing, it will be created if it does not already exist and it will be reset if it does, resulting in the deletion of any data already there. Using the w indicates that the file is assumed to be a text file.

Here is the program to create a file and write some data into the file.

#include <stdio.h>
int main()
{
 FILE *fp;
 file = fopen("file.txt","w");
 /*Create a file and add text*/
 fprintf(fp,"%s","This is just an example :)"); /*writes data to the file*/
 fclose(fp); /*done!*/
 return 0;
}

Appending (a)

When a file is opened for appending, it will be created if it does not already exist and it will be initially empty. If it does exist, the data input point will be positioned at the end of the present data so that any new data will be added to any data that already exists in the file. Using the a indicates that the file is assumed to be a text file.

Here is a program that will add text to a file which already exists and there is some text in the file.

#include <stdio.h>
int main()
{
    FILE *fp
    file = fopen("file.txt","a");
    fprintf(fp,"%s","This is just an example :)"); /*append some text*/
    fclose(fp);
    return 0;
}

Outputting to the file

The job of actually outputting to the file is nearly identical to the outputting we have already done to the standard output device. The only real differences are the new function names and the addition of the file pointer as one of the function arguments. In the example program, fprintf replaces our familiar printf function name, and the file pointer defined earlier is the first argument within the parentheses. The remainder of the statement looks like, and in fact is identical to, the printf statement.

Closing a file

To close a file you simply use the function fclose with the file pointer in the parentheses. Actually, in this simple program, it is not necessary to close the file because the system will close all open files before returning to DOS, but it is good programming practice for you to close all files in spite of the fact that they will be closed automatically, because that would act as a reminder to you of what files are open at the end of each program.

You can open a file for writing, close it, and reopen it for reading, then close it, and open it again for appending, etc. Each time you open it, you could use the same file pointer, or you could use a different one. The file pointer is simply a tool that you use to point to a file and you decide what file it will point to. Compile and run this program. When you run it, you will not get any output to the monitor because it doesn’t generate any. After running it, look at your directory for a file named TENLINES.TXT and type it; that is where your output will be. Compare the output with that specified in the program; they should agree! Do not erase the file named TENLINES.TXT yet; we will use it in
some of the other examples in this section.

Reading from a text file

Now for our first program that reads from a file. This program begins with the familiar include, some data definitions, and the file opening statement which should require no explanation except for the fact that an r is used here because we want to read it.

#include <stdio.h>
   main( )
   {
     FILE *fp;
     char c;
     funny = fopen("TENLINES.TXT", "r");
     if (fp == NULL)
		printf("File doesn't exist\n");
     else {
      do {
       c = getc(fp); /* get one character from the file
       */
         putchar(c); /* display it on the monitor
       */
       } while (c != EOF); /* repeat until EOF (end of file)
     */
     }
    fclose(fp);
   }

In this program we check to see that the file exists, and if it does, we execute the main body of the program. If it doesn’t, we print a message and quit. If the file does not exist, the system will set the pointer equal to NULL which we can test. The main body of the program is one do while loop in which a single character is read from the file and output to the monitor until an EOF (end of file) is detected from the input file. The file is then closed and the program is terminated. At this point, we have the potential for one of the most common and most perplexing problems of programming in C. The variable returned from the getc function is a character, so we can use a char variable for this purpose. There is a problem that could develop here if we happened to use an unsigned char however, because C usually returns a minus one for an EOF – which an unsigned char type variable is not
capable of containing. An unsigned char type variable can only have the values of zero to 255, so it will return a 255 for a minus one in C. This is a very frustrating problem to try to find. The program can never find the EOF and will therefore never terminate the loop. This is easy to prevent: always have a char or int type variable for use in returning an EOF. There is another problem with this program but we will worry about it when we get to the next program and solve it with the one following that.

After you compile and run this program and are satisfied with the results, it would be a good exercise to change the name of TENLINES.TXT and run the program again to see that the NULL test actually works as stated. Be sure to change the name back because we are still not finished with TENLINES.TXT.

Pages: [Page - 1] [Page - 2] [Page - 3] [Page - 4]

Tags: , ,

There are 277 Comments to this post. You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response or TrackBack from your own site.

  • c-prog boy says:

    How can i put files (save,load,delete) on structures using c++ ?
    please show some examples (codes).

  • Hai friends! I want to details of file handling in depth for making the database in c and c++. Because I want to make a project using the file handling and database in c and c++.

  • sriram says:

    Hi guys and gals. i’ve gotta submit a project. I have to handle student details such as name, roll number, 5 marks, avg,result and rank. i need to save it in a file using C. could you plz help me gettin the codes. plz.

  • rajen says:

    there is a software which ask to select the file path , but i always need the same file(same path).i want to automise this process by using c/c++.i.e the file is automatically available to it. please help me(atleast some tips).u can mail me on rajrock4692003 at yahoo dot co.in

  • mekala says:

    How to read and compare a two files in c language and print the same object in one file

  • Agasthi says:

    For reading a file the file needs to be created using c program. or we can read file that is created manually.

  • CARRY says:

    HOW TO CALCULATE BODY MASS INDEX? CAN YOU TELL ME THE CODING?I CAN’T GET THE ANSWER.PLEASE HELP ME…..plz email me at satorare_hatsumei_kannipan at yahoo dot com

  • jamkie says:

    how to use database in C language?

  • learner says:

    This example is from C example. If I don’t use the constant char: char string[] = “This is a test”. If I need to put varies CHARs into the string[], how I can do? Can you give me an example?

    • saqib says:

      Quote: This example is from C example. If I don’t use the constant char: char string[] = “This is a test”. If I need to put varies CHARs into the string[], how I can do? Can you give me an example?

      Learner, what do you mean by the question? Do want to use the varied length array os characters?
      If it is so then I think you can use char* string[] for as many characters as you would like to.

  • sri says:

    Hi I want file handling in Visual C+. Lke geting content of the file.txt and show in to list control

    • saqib says:

      Here is the code that will get the contents of a file and then show them into the list box control using VC++

         FILE *stream;
         char string[] = "This is a test";
         char msg[20];
         /* open a file for update */
         stream = fopen("FILE.txt", "w+");
         /* write a string into the file */
         fwrite(string, strlen(string), 1, stream);
         /* seek to the start of the file */
         fseek(stream, 0, SEEK_SET);
         /* read a string from the file */
         fgets(msg, strlen(string)+1, stream);
         //now in msg string u have all the contents of the fild.
        //now u can add it to the list easly.
         ListCtrl.AddString(msg);
         fclose(stream);

      Hopefully u can get the point , that how to return the text from the file in a string and add it to the list control.
      Although it is not a complete code of VC++ but still it may help you.

  • Amit says:

    I have to read chracters from a file and printed them on screen as in first “5765″ in second “67866 ” ans so on

  • sukanya says:

    I have to give run time entries in after opening file in append mode(the file already exists and it contains the name and ID of students)….can u please give me some examples.my mail ID is suku_the_smart at yahoo dot co.in

  • My question:

    Write a program to find or count articles (a,an,the) in text file?

  • Gopikrishnan says:

    i need a program to create symboltable using files in c plz help me

  • DarK_SouL says:

    hi evryone. I would like to know about implementing database systems in C using data files and other C features… thanks…

  • badet says:

    please give me a sample program implementing database or data files handling in C. e-mail me at bc_macaraig@yahoo.com.ph. Thanks

  • RUSTY PALLER says:

    PLEASE GIVE SOME CLEAR EXAMPLE TURBO C PROGRAM THAT WOULD OPEN,EDIT AND WRITE A CERTAIN FILE WHICH IS NOT CONNECTED TO THE MAIN PROGRAM BASE ON ITS FILE NAMES.I HOPE I CAN RECIEVE THE ANSWER AS SOON AS POSSIBLE BECAUSE THI WILL SERVES AS MY FINAL REPORT IN TURBO C SUBJECT

  • nandika says:

    Please tell me the difference between the pragramme and file. As we can make records of students in c programme also then for what purpose exactly we need files.

  • Rachna Jain says:

    Hi all,
    I want 2 know about the Complete graphics programming in C Lang, Could you give me some correct URL in which all graphics tutorials are stored.
    Thnx.

  • prithvi says:

    how to delete a single line from a text file using streams where each line is ended with new line char

    • LOGANATHAN.S says:
      #include <stdio.h>
      #include <dos.h>
      
      void  main()
      {
      FILE *fp,*fp1;
      int k=1,input,c;
      clrscr();
      fp=fopen("test.txt","r");
      fp1=fopen("test1.txt","w");
      puts("
      Enter The Line Number To Delete");
      scanf("%d",&input);
      while(26)
      {
      
      if(c=='
      ')
          k++;
      c=fgetc(fp);
      if(feof(fp))
      	break;
      
      if(input!=k)
          fputc(c,fp1);
      
      }
      fcloseall();
      remove("test.txt");
      rename("test1.txt","test.txt");
      getch();
      }
      
  • I linked a Datafile Data.TXT (Create in MS DOS TAB/Space formate) and how I Read/Write each field for other purpose.

  • k.indhumathi says:

    i need the program for the following outputs

    aaa111bbb222……000111

  • robert says:

    Please do for me this question.. I am really in hurry!!
    Assuming that the pre-registration process has not been exercised. Now, you will try to create a similar system that will have somewhat the same function of the real system using C programming. First, the system will ask for your matric number or name to check whether you exist in the record, if your name or matric number does not exist, the system will create a new profile of your name and matric number. The system must have the following features where it can add subjects, drop subjects, print the subjects chosen to the screen, check the availability of a course and vacancies in a class so that it should not exceed the maximum number of students in a single class. The system also checks whether the student fulfills his/her minimum or maximum credit hour for one semester. In our case, the system should alert the user if he/she has not fulfilled the required credit hours. Also, alert the user if the class has no vacancies or in other words the class is full. In this system, the maximum credit hour allowed is 18 credits and the minimum is 12 credits. A single class is dissolved if the students in a class are less than 5 people and then the system will put the students in a waiting list. A class will split into two if and only if the number of students exceed the class limit of 50 and the extra students is not less than 10 (where students in the waiting list must be more than 10 for that particular subject). Also, the CGPA of the student should be considered in determining the credit hours. A CGPA of more than 2.6 will allow the student to register a maximum of 18 credits while a student that obtains a CGPA less than 2.6 but more that 2.4, can only register to a maximum of 15 credits. A student with a CGPA less than 2.4 will have to see the Deputy Dean of Student Affairs for approval. Prompt out an alert message for students with CGPA less than 2.4 to meet the Deputy Dean of Student Affairs to register that particular semester
    pleeeeeeeeeassss……

  • larish says:

    what is the c program for comparing the two files and copying the first ten characters of first file to the second file..please answer.it breaks my head..thank you

    • 1.open two files(fp1,fp2) one is for read,one is for write
      2.initialize for count(int count++;)
      2.save your text in read file.
      3.open two files(fp1=for read,fp2=for write)
      4.while(c=getc(fp1)!=EOF)
      {
      putc(c,fp2);
      count++;
      if(count==10)
      exit();
      }
      5.close the files

      if u have doubt mail me.

      ——– Original Message ——–
      what is the c program for comparing the two files and copying the first ten characters of first file to the second file..please answer.it breaks my head..thank you

  • can we delete data from file in c if yes then how?

  • riya says:

    plz can u solve the problem?
    Suppose there is a file that contains the meaning of words
    E.G.

    apple – a fruit
    cricket – a game
    User would enter a word as input and the program would search for the meaning of the word from the file and display on screen. If the word is not found then display appropriate message.

    • LOGANATHAN.S says:

      TEXT FILE : apple-a fruit cricket-a game

      ----------------------------
        C-File has
      ----------------------------
      #include <stdio.h>
      void main()
        {
        FILE *fp=fopen("logu.txt","r");
        int x,c,i=0,j=0;
        char a[45],b[45];
        clrscr();
        puts("Enter The Word To Search");
        scanf("%s",b);
        while(26)
        {
      	  if(feof(fp))
      	  break;
      	  x=fgetc(fp);
      	  if(x!='-')
      	  {
      		  a[j]=x; j++; continue;}
      		  a[j]='�';
      		  if(strcmp(a,b)==0)
      		  {
      			  while(45)
      			  {
      				  x=fgetc(fp);
      				  if(x=='  ')
      				  break;
      				  printf("%c",x);
      			  }
      			  getch();
      			  exit(0);
      		  }
      		  else
      		  {
      			  while(46)
      			  {
      				  x=fgetc(fp);
      				  if(x==' ')
      				  break;
      			  }
      		  }
      		  j=0;
      	  }
      	  puts("No Word To Be Match");
      	  getch();
        }

      ———————————————–
      mail:logu.lmg@gmail.com

  • babu.s says:

    Write a program for reading a file thru a 20 byte Structure and to display and then write it using same structure in another file.
    The input file will contain some 100 or so characters.
    plz solve it 4 me

  • melissa says:

    how to encrypt a file??

  • XXX says:

    I have done the encryption in java programming which will generate some license file.Now i want to decrypt that license file content using C programming.If anybody have any idea pls help me..
    Thanks in advance..

    XXX

    • Sarfraz says:

      first of all u should know the encryption mode which u r using & accordingly the decryption key…once u get this u can come up with ur own decryption algorithm by including it.

      ——– Original Message ——–
      I have done the encryption in java programming which will generate some license file.Now i want to decrypt that license file content using C programming.If anybody have any idea pls help me..
      Thanks in advance..

      XXX

  • XXX says:

    HI friends,

    I want to encrypt and decrypt the details using DES in C language.I dont know much about C.If anybody have any idea pls let me know…

    Thanx in advance.

  • dels says:

    how would i go about writing code that reads in data from a txt file then sends it via a RS232 cable (to control a motor.) thanks.

  • how to create a program for random selecting of records in a file using c language??????

  • Tarun says:

    can u right a progrma in file that after execution kills itself

  • murugan says:

    I want to display my result (Use c++ code) in particular difined pixels for example to diplay centre of screen.

  • How to copy constants from one file to anothre file using c code.

  • Prathap says:

    Hi, This is Prathap, I want some example programs o n file I/O

    How to open a file and how to read and write a file.
    I have read the content which u have given.But I couldn’t understand the concept. Please suggest some sample programs and content for that

  • harshad says:

    I have done structure prog. which is accept the name & age of student & also modify the data in it or delete it,now i wanted to store this prog. in file,but i dont know how to do that ..

    & also gives o/p which last store in stuct prog.

  • Sangram says:

    I want the code in C,where it will print first 10 lines,middle 10 lines and last 10 lines of a file.

    Plz ,send to my mail:sangram07_406@rediffmail.com

    I will wait for ur replay.
    Thank u.

    From,
    sangram keshari panda

  • I want various program of file handling inc and i want notes of basics of AS 400.plz guide me.

  • sw says:

    can somebody plz tell me how to access and update a column in a file if the file is written in a column format?

  • priya says:

    Please guide me to write c code for the follwing program
    “to direct the even and odd numbers to the respective files even.txt and odd.txt.Given a list of 10 numbers”

    Thank you
    priya

    • Dhananjay says:

      As you check the nos. for odd and even…..say by using modulus operator store the even nos in one array and odds in another.
      use File pointer to open two new files and write those arrays onto it.

      FILE *fp; //declared above
      int ev[20];odd[20];
      fp=fopen(“even.txt”,”w”);
      fprintf=(“%d”,even);
      fclose(fp);

      dj
      dhananjaynu@gmail.com

      ——– Original Message ——–
      Please guide me to write c code for the follwing program
      “to direct the even and odd numbers to the respective files even.txt and odd.txt.Given a list of 10 numbers”

      Thank you
      priya

      • priya says:

        thank you

        ——– Original Message ——–

        As you check the nos. for odd and even…..say by using modulus operator store the even nos in one array and odds in another.
        use File pointer to open two new files and write those arrays onto it.

        FILE *fp; //declared above
        int ev[20];odd[20];
        fp=fopen(“even.txt”,”w”);
        fprintf=(“%d”,even);
        fclose(fp);

        dj
        dhananjaynu@gmail.com

        ——– Original Message ——–
        Please guide me to write c code for the follwing program
        “to direct the even and odd numbers to the respective files even.txt and odd.txt.Given a list of 10 numbers”

        Thank you
        priya

        • kkk says:

          Please change this line

          fprintf=(“%d”,even);
          by
          fprintf=(fp,”%d”,even);

          ——– Original Message ——–
          thank you

          ——– Original Message ——–

          As you check the nos. for odd and even…..say by using modulus operator store the even nos in one array and odds in another.
          use File pointer to open two new files and write those arrays onto it.

          FILE *fp; //declared above
          int ev[20];odd[20];
          fp=fopen(“even.txt”,”w”);
          fprintf=(“%d”,even);
          fclose(fp);

          dj
          dhananjaynu@gmail.com

          ——– Original Message ——–
          Please guide me to write c code for the follwing program
          “to direct the even and odd numbers to the respective files even.txt and odd.txt.Given a list of 10 numbers”

          Thank you
          priya

    • int num;
      ifstream fin;
      fin.open("NUMBERS.TXT",ios::in);
      ofstream fout1,fout2;
      fout1.open("even.txt");
      fout2.open("odd.txt");
      while(!fin.eof())
      {
       fin>>num;
       if(num %2==0)
          fout1<<num<<endl;
       else if(num%2!=0)
          fout2<<num<<endl;
      }
      fout1.close();
      fout2.close();
      fin.close();
      
      
  • Neelu says:

    I need to open 20 files at a time, and read data from them. Then I have to process this data. But when my ifstream object reads, until 12 files it works fine, then after that, it just reads zeros. Please let me know, how many files can maximum at a time be opened in C++ file handling programs for processing. if it is less than or equal to 12, then is any other way out.
    please help somebody.

  • peng says:

    i need to read a data from a file by word..can someone help me with this code??another problem of mine is that i need to have an mdi form in c language..is it possible??if then..please help me with this matter…Thanks and Godbless!!!

  • Jyoti says:

    Please solve this query for me
    How to write one or more records in C

  • manisha says:

    1)write an algorithm/program that accepts an input as a decimal number and convert it into binary representation?in “c” program
    2)what is file handling?create a program to count the number of digits in a file?in “c”
    3)write a program to fectorial of a number using recursion?in “c”
    4)write a program to sort an two dimentional array using bubble sorting in “c++” language

    • Rohitash says:

      ——– Original Message ——–
      1)write an algorithm/program that accepts an input as a decimal number and convert it into binary representation?in “c” program
      2)what is file handling?create a program to count the number of digits in a file?in “c”
      3)write a program to fectorial of a number using recursion?in “c”
      4)write a program to sort an two dimentional array using bubble sorting in “c++” language

      The Answer of your 3′rd ques, is

      /*  Program to factorial opf a no. using recursion  */
        #include<stdio.h>
        #include<conio.h>
        int fact(int n);
        void main()
        {
      	  int n,res;
      	  printf("
      	  Enter the no. that u want");
      	  scanf("%d",&n);
      	  res=fact(n);
      	  printf("
      	  The factorial of the no. that you   enter is");
      	  printf("%d",res);
      	  getch();
        }
      
      int fact(int n)
        {
        	if(n==1) 
        		return(1);
        else
        		return (n*fact(n-1));
        }
      
  • manisha says:

    1)write a script that accept two strings from user and compare two strings?in web technologies

  • tanu says:

    hi pls help me i want some notes on input/output files for preparing my seminar

  • read the code:
    FILE* fp;
    fp=fopen(filename,”r”);
    char c;
    c=getc(fp)
    while(c != EOF)
    {c=getc(fp);
    }
    ——————————–
    now…if I want of access first character of file…means to go back at start of file….how I wil do this?
    without closing file.
    Is there any function availble in ‘C’?

  • There is a Text file in C .How to print the contents of file in the reversing order.
    eg “Hello How are You”
    “uoy era woH olleH”
    Describe the most relevant way


Leave a Reply

You must be logged in to post a comment.