Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,239 questions

56,142 answers

573 users

How to implement the function fgets() from stdio.h that read characters (string) from a file in C

3 Answers

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

char *my_fgets(char *s, int n, FILE *fp);
 
int main(void)
{
    char buf[100];
    
    if (!my_fgets(buf, sizeof(buf), stdin) && ferror(stdin))  {
        fprintf(stderr, "%s: error reading stdin\n", buf);
        exit(EXIT_FAILURE);
    }
    puts(buf);

     
    return 0;
}
char *my_fgets(char *s, int n, FILE *fp)
{
    int c;
    char *ch;

    ch = s;
    while (--n > 0 && (c = getc(fp)) != EOF)
        if ((*ch++ = c) == '\n')
            break;
    *ch = '\0';
    
    return (c == EOF && ch == s) ? NULL : s;
}

 
/*
run:
   
read characters from stream with my_fgets
read characters from stream with my_fgets

*/

 



answered Dec 22, 2015 by avibootz
0 votes
#include <stdio.h>

char *my_fgets(char *s, int n, FILE *fp);
 
int main(void)
{
    char buf[100];
    
    my_fgets(buf, sizeof(buf), stdin);
    puts(buf);

     
    return 0;
}
char *my_fgets(char *s, int n, FILE *fp)
{
    int c;
    char *ch;

    ch = s;
    while (--n > 0 && (c = getc(fp)) != EOF)
        if ((*ch++ = c) == '\n')
            break;
    *ch = '\0';
    
    return (c == EOF && ch == s) ? NULL : s;
}

 
/*
run:
   
hello from stdin
hello from stdin

*/

 



answered Dec 22, 2015 by avibootz
edited Dec 22, 2015 by avibootz
0 votes
#include <stdio.h>

char *my_fgets(char *s, int n, FILE *fp);
 
int main(void)
{
    char buf[100];
    FILE *fp;
    
    fp = fopen ("e:/index.htm" , "r");
    if (fp == NULL) perror("Error open file");
    my_fgets(buf, sizeof(buf), fp);
    puts(buf);
    fclose(fp);

     
    return 0;
}
char *my_fgets(char *s, int n, FILE *fp)
{
    int c;
    char *ch;

    ch = s;
    while (--n > 0 && (c = getc(fp)) != EOF)
        if ((*ch++ = c) == '\n')
            break;
    *ch = '\0';
    
    return (c == EOF && ch == s) ? NULL : s;
}

 
/*
run:
   
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transi...

*/

 



answered Dec 22, 2015 by avibootz
edited Dec 22, 2015 by avibootz
...