fgetc and fputc in c

24 Dec 2022 Balmiki Mandal 0 C Programming

fgetc and fputc are two standard library functions in the C programming language that are used to read and write characters to a file. fgetc is used to read a character from a file. It takes a file pointer as its argument and returns the next character from the file. If the end of the file is reached, EOF is returned. fgetc() and fputc() are file input/output functions in the C programming language.

 

what does mean of fgetc in c programming

fgetc() the function is used to read a single character from a file. The syntax of fgetc() the function is as follows:

⇒upon success, it will return the character ASCII which faced

⇒upon failure, it returns -1

-1 is the end of the file 

Here's an example of using fgetc to read a file character by character:

#include 

int main() {
    FILE *fp;
    int c;

    fp = fopen("myfile.txt", "r");
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }

    while ((c = fgetc(fp)) != EOF) {
        printf("%c", c);
    }

    fclose(fp);
    return 0;
}

In this example, we open the file "myfile.txt" in read mode and read each character from the file using fgetc until we reach the end of the file.

 

what does mean of fputc in c programming

fputc, on the other hand, is used to write a character to a file. It takes two arguments: the character to write and a file pointer. It returns the character written, or EOF on error.

Here's an example of using fputc to write to a file:'

#include 

int main() {
    FILE *fp;
    char c = 'a';

    fp = fopen("myfile.txt", "w");
    if (fp == NULL) {
        perror("Error opening file");
        return -1;
    }

    while (c <= 'z') {
        fputc(c, fp);
        c++;
    }

    fclose(fp);
    return 0;
}

In this example, we open the file "myfile.txt" in write mode and write the characters 'a' through 'z' to the file using fputc. Finally, we close the file.

 

#include
void main(int argc,char **argv)
{
    FILE *fp;
    char ch;
    if(argc!=2)
    {
        printf("usage:./a.out fname\n");
        return;
    }
    fp=fopen(argv[1],"r");
    if(fp==0)
    {
        printf("File not present..\n");
        return;
    }
    while((ch=fgetc(fp))!=-1)
    printf("%c",ch);
}

 

 

 

BY: Balmiki Mandal

Related Blogs

Post Comments.

Login to Post a Comment

No comments yet, Be the first to comment.