fputc() & fgetc() in C programming
File Handling: fputc() & fgetc() in C programming
fputc() and fgetc() are file handling function in C programming that are used to operate on data and strings present in the file. The perform different function and are used in different situation according to the needs.fputc() & fgetc() in C programming:
- fputc()- It is used to write a single character into an already opened file, i.e. to a specified stream. Its writes a given character at the position given by the file pointer into a file.
- fgetc()- It is used to get a single character from the file into the output console. It returns the character present at the pointer and displays it.
Syntax of fputc()
int fputc(int character, FILE *stream)
Various part of Syntax:
- Character- It represents the character that is to be inserted into the stream
- Stream- It is used as a pointer which points at the stream or file where the character is to be written.
Example:
Run
#include<stdio.h> int main () { FILE *new; int character; new = fopen("file.txt", "w+"); for( character = 19 ; character <= 100; character++ ) { fputc(character, new); } fclose(new); return(0); }
Output:
A file will be created with charatcers from 19 to 100.
An error message will be displayed while compiling this code in online compiler as file handling is done on computer memory.
Syntax of fgetc():
int fgetc(FILE *point)
Pointer- It is used as a pointer which identifies the stream or file where the character is to be written by the operator.
Example 2:
Run
#include<stdio.h> #include<conio.h> void main() { FILE *new; char character; clrscr(); new=fopen("sample.txt","r"); while((character=fgetc(new))!=EOF) { printf("%c",character); } fclose(new); getch(); }
Alert
This code might not run in online compiler , as file handling work on Computer memory .
Output:
//Some simple text message or data of the file will be displayed.
Example using fputc() & fgetc() in C programming:
Run
#include<stdio.h> int main() { int i = 0; FILE *new = fopen("test.txt","w"); if (new == NULL) { return 0; } char string[] = "good bye", rec_string[20]; for (i = 0; string[i]!='\0'; i++) { fputc(string[i], new); } fclose(new); newf = fopen("test.txt","r"); fgets(rec_string,20,new); printf("%s", rec_string); fclose(newf); return 0; }
Output:
good bye
Explanation of code:
- In the first part of the code test file is opened in write mode and fputc() is used to insert “good bye” into the test file.
- In the last part of code, the test file is opened in read mode and fgets() is used to read the content of the file and display it on the stdout console.
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment