How to write to a file in c









#include<stdio.h>
int main(){
        FILE *ptr; //It is file pointer
        char c;

        //opening the file in write mode in Linux os
        ptr = fopen("/root/Test/abc.txt","w");

        //Opening the file in write mode in window os
        // ptr = fopen("C:\\Test\\abc.txt","r");

        //Checking the path is valid or not and printing message
        if(ptr == NULL)
                printf("Error in opening the file");
        else
                printf("File has opened successfully in read mode");
   
    //Write text in the file
    printf("\nEnter text to write in the file and press Esc key to end : ");
    c = getchar();
     while(c!= 27){  //27 is ASCII value of Esc key.
         putc(c,ptr); //Printing one character in file.
         c = getchar();  //getting one character from keybord.
        }

    //Closing the opened file
    fclose(ptr);
    
return 0;
}








No comments: