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
...