C Open File

Description

You open a file by calling function fopen(), which returns the file pointer for a file.

Syntax

The function fopen() is defined in <stdio.h>, and it has this prototype:

FILE *fopen(char *name, char *mode);

Parameter

The first argument is the file name in string. The second argument is a character string called the file mode that specifies what you want to do with the file.

Mode

The following table lists these three file modes.

Mode Description
"w" Open a text file for write operations. If the file exists, its current contents are discarded.
"a" Open a text file for append operations. All writes are to the end of the file.
"r" Open a text file for read operations.

Example 1


#include<stdio.h>
/*w w w.  j  a  va2s  .c om*/
void main(){
    FILE *fp;

    fp = fopen("test.txt","a");
    fprintf(fp,"%d %s %d\n",1,"java2s.com",2);

    fclose(fp) ;
}

Example 2


#include "stdio.h"
/*from   w  w  w.  j  a  va 2  s  .c  om*/
int main() {
    FILE *fp;
    
    int letter;

    if( ( fp = fopen( "my.txt", "r")) == NULL) {
        puts("Cannot oepn the file");
        exit( 0 );
    }
    while( ( letter = fgetc( fp ) ) != EOF)
        printf("%c",letter);
    fclose(fp);
}




















Home »
  C Language »
    Language Advanced »




File
Function definition
String
Pointer
Structure
Preprocessing