Q:

C program to create, write and read text in/from file

0

C program to create, write and read text in/from file

Here, we are going to learn all about file handling with examples in C programming language, following topics we are going to cover in this article:

  • Creating variable of file pointer
  • Opening/creating a file
  • Write some of the characters in a file
  • Reading one by one character from a file
  • Closing a file
  • And with second example
    • Writing continuous text (complete paragraph until we do not press any special character defined in program).
    • Reading all text until EOF (End of the file) is not found.
  • And closing the file

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we are writing some of the characters (without taking input from the keyboard) and reading, printing , written characters.

#include< stdio.h >
int main()
{
 
    FILE *fp;   /* file pointer*/
    char fName[20];
 
    printf("\nEnter file name to create :");
    scanf("%s",fName);
 
    /*creating (open) a file*/
    fp=fopen(fName,"w");
    /*check file created or not*/
    if(fp==NULL)
    {
        printf("File does not created!!!");
        exit(0); /*exit from program*/
    }
 
    printf("File created successfully.");
    /*writting into file*/
    putc('A',fp);
    putc('B',fp);
    putc('C',fp);
 
    printf("\nData written successfully.");
    fclose(fp);
 
    /*again open file to read data*/
    fp=fopen(fName,"r");
    if(fp==NULL)
    {
        printf("\nCan't open file!!!");
        exit(0);
    }
 
    printf("Contents of file is :\n");
    printf("%c",getc(fp));
    printf("%c",getc(fp));
    printf("%c",getc(fp));
 
    fclose(fp);
    return 0;
}

Output

Enter file name to create : ok.txt
File created successfully.
Data written successfully.
Contents of file is :
ABC

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

File Handling Examples Programs in C language

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C program to print given number of lines of a file... >>
<< C program to create a text file using file handlin...