Most important Topic : File input/output functions with examples


 

--------------------------------------

        File modes

--------------------------------------

r     | open an existing file


w     | open flle for writing..if file not  exist then create...(old data  removed)


a      | same as w mode...(old data not removed)


r+    |  you do reading and writing at same time
          

w+   |  same as w mode but here  also read...in w mode you can't read...(old data removed)


a+    |  reading and writing (old data not  removed)


-------------------------------------

File Functions

-------------------------------------

fscanf:  see in example

fprintf: see in example


fputc:  Enter character in file

            fputc(character,file pointer);

fputs:  Enter string in file

            fputs(string,file pointer);


fgetc:   Read character from file

            fgetc(File pointer);       

fgets:    Read string from file

              fgets(const char*s,int n,File pointer);

-------------------------------------

                     Example

-------------------------------------

#include<stdio.h>

int main(){

        // Reading

FILE *ptr =NULL;

char string[34];

ptr=fopen("rrrrr.txt","r");

fscanf(ptr,"%s",string);

printf("The content of the file: %s",string);

       // Writing

FILE *ptr =NULL;

char string[34];

ptr=fopen("rrrrr.txt","w");

fprintf(ptr,"%s",string);

      //appending

FILE *ptr =NULL;

char string[34];

ptr=fopen("rrrrr.txt","a");

fprintf(ptr,"%s",string);

return 0;

}

--------------------------------------------------

fgets/fgetc/fputs/fputc

--------------------------------------------------

fgetc

#include<stdio.h>

int main(){

FILE *ptr= NULL;

ptr = fopen("rrrrr.txt","r");

char c = fgetc(ptr);

printf("The character i read was %c\n",c);

c = fgetc(ptr);

printf("The character i read was %c\n",c);

flose(ptr);

return 0;

}

fgets

#include<stdio.h>

int main(){

FILE * ptr =NULL;

ptr = fopen("rrrrr.txt","r");

char str[34];

fgets(str,5,ptr);

printf("THe string is %s\n", str); 

flose(ptr);

}

fputs

#include<stdio.h>

int main(){

FILE *ptr=NULL;

ptr= fopen("rrrrr.txt","a+");

fputc('o',ptr);

fputs("This is harry g",ptr);

fclose(ptr);

return 0;

}

Fgets

#include<stdio.h>

int main(){

FILE *ptr= NULL;

ptr = fopen("rrrrr.txt","r");

char str[4];

fgets(str,5,ptr);

printf("The string is %s\n",str);

fclose(ptr);

return 0;

}








Comments