how to write the data in file and read data from code example

Example 1: c program to read and write to a file

/*Program to read from file using getc() function*/
#include <stdio.h>
int main() {
 FILE *fp;
 char ch;
 /*Open file in read mode*/
 fp= fopen ('example.txt', 'r');
 while( (ch = getc(fp)) != EOF) {
  /*getc() function reads a character and its value is stored in variable 'ch' until EOF is encountered*/
  printf('%ch', ch);
 }
  fclose(fp);
  return 0;
}

Example 2: how to create a file in c

/**
 * C program to create a file and write data into file.
 */

#include <stdio.h>
#include <stdlib.h>

#define DATA_SIZE 1000

int main()
{
    /* Variable to store user content */
    char data[DATA_SIZE];

    /* File pointer to hold reference to our file */
    FILE * fPtr;


    /* 
     * Open file in w (write) mode. 
     * "data/file1.txt" is complete path to create file
     */
    fPtr = fopen("data/file1.txt", "w");


    /* fopen() return NULL if last operation was unsuccessful */
    if(fPtr == NULL)
    {
        /* File not created hence exit */
        printf("Unable to create file.\n");
        exit(EXIT_FAILURE);
    }


    /* Input contents from user to store in file */
    printf("Enter contents to store in file : \n");
    fgets(data, DATA_SIZE, stdin);


    /* Write data to file */
    fputs(data, fPtr);


    /* Close file to save file data */
    fclose(fPtr);


    /* Success message */
    printf("File created and saved successfully. :) \n");


    return 0;
}

Tags:

Cpp Example