C Programs on File Handling

C Program to Write a Sentence to a File

Code:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char Line[1000];
    FILE *fp;
    fp = fopen("file.txt", "w");
    if (fp == NULL)
    {
        printf("Error!");
        exit(1);
    }
    printf("Enter a Line: ");
    fgets(Line, sizeof(Line), stdin);
    fprintf(fp, "%s", Line);
    fclose(fp);
    return 0;
}

Output:

Enter a Line: Welcome To Codedec

C Program to write character values in a file using Function putc()

Code:

#include<stdio.h>
int main()
{
    FILE *f1;
    char c;
    printf("INPUT\n");
    
    f1 = fopen("INPUT","w");
    while((c=getchar())!=EOF)
    {
        putc(c,f1);
    }
    fclose(f1);
    printf("OUTPUT\n");
    f1=fopen("INPUT","r");
    while((c=getc(f1))!=EOF)
    {
        printf("%c",c);
    }
    fclose(f1);
    return 0;
}

Output:

INPUT
THIS IS A TEST PROGRAM
OUTPUT
THIS IS A TEST PROGRAM

C Program to Read a Line From a File and Display it

Code:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char data[500];
    FILE *fp;
    if ((fp = fopen("program.txt", "r")) == NULL)
    {
        printf("Error!");
        exit(1);
    }
    fscanf(fp, "%[^\n]", data);
    printf("Data output: %s\n", data);
    fclose(fp);

    return 0;
}

Output:

Data output: Welcome To Codedec

C Program to Display its own Source Code as Output

Code:

#include <stdio.h>
int main()
{
    FILE *fp;
    int line;
    fp = fopen(__FILE__,"r");

    do {
         line = getc(fp);
         putchar(line);
    }
    while(line != EOF);
    fclose(fp);
    return 0;
}

Output:

#include <stdio.h>
int main()
{
    FILE *fp;
    int line;
    fp = fopen(__FILE__,"r");

    do {
         line = getc(fp);
         putchar(line);
    }
    while(line != EOF);
    fclose(fp);
    return 0;
}