Reading c file line by line with fgetc ()

Here's how I did it, but I'm not sure if this is the preferred idiom:

FILE *fp = fopen(argv[0], "r");
// handle fopen() returning NULL

while (!feof(fp)) {
    char buffer[80]; // statically allocated, may replace this later with some more sophisticated approach
    int num_chars = 0;

    for (int ch = fgetc(fp); ch != EOF && ch != '\n'; ch = fgetc()) {
        buffer[num_chars++] = ch;
    }

    // null-terminate the string
    buffer[num_chars] = '\0';

    printf("%s\n", buffer);
}

That's good, any suggestions for improving this?

+5
source share
6 answers

If you are not going to use fgets()(perhaps because you want to delete a new line or want to deal with the end of a line "\r", "\n"or "\r\n"), or you want to know how many characters have been read), you can use this as a skeleton function:

int get_line(FILE *fp, char *buffer, size_t buflen)
{
    char *end = buffer + buflen - 1; /* Allow space for null terminator */
    char *dst = buffer;
    int c;
    while ((c = getc(fp)) != EOF && c != '\n' && dst < end)
        *dst++ = c;
    *dst = '\0';
    return((c == EOF && dst == buffer) ? EOF : dst - buffer);
}

; . ; , , , ; . , - 1, , , - :

int get_line(FILE *fp, char *buffer, size_t buflen)
{
    char *end = buffer + buflen - 1; /* Allow space for null terminator */
    char *dst = buffer;
    int c;
    while ((c = getc(fp)) != EOF && dst < end)
    {
        if ((*dst++ = c) == '\n')
            break;
    }
    *dst = '\0';
    return((c == EOF && dst == buffer) ? EOF : dst - buffer);
}

, , . DOS, () Mac Unix, CSV- " " Kernighan Pike ( ) :

static int endofline(FILE *ifp, int c)
{
    int eol = (c == '\r' || c == '\n');
    if (c == '\r')
    {
        c = getc(ifp);
        if (c != '\n' && c != EOF)
            ungetc(c, ifp);
    }
    return(eol);
}

c != '\n':

int get_line(FILE *fp, char *buffer, size_t buflen)
{
    char *end = buffer + buflen - 1; /* Allow space for null terminator */
    char *dst = buffer;
    int c;
    while ((c = getc(fp)) != EOF && !endofline(fp, c) && dst < end)
        *dst++ = c;
    *dst = '\0';
    return((c == EOF && dst == buffer) ? EOF : dst - buffer);
}

fread() fwrite():

void copy_file(FILE *in, FILE *out)
{
    char buffer[4096];
    size_t nbytes;
    while ((nbytes = fread(buffer, sizeof(char), sizeof(buffer), in)) != 0)
    {
        if (fwrite(buffer, sizeof(char), nbytes, out) != nbytes)
            err_error("Failed to write %zu bytes\n", nbytes);
    }
}

, :

copy_file(fp, stdout);
+12

char, - , fgets. fgets.

 fgets (buffer, BUFFER_SIZE, fp);

, fgets , EOF (, , ). "\n" , . .

fgets:

str.
End-of-File , str .
, .
ferror, feof, , .

+1

, 80 .

ThiefMaster: fgets(). , , , , .

+1

, fgets().

, fgets(), "" num_chars.

fgets(buffer, sizeof buffer, stdin);
fputs(buffer, stdout); /* buffer contains a '\n' */

'\n'

buffer[0] = 0;
if (!fgets(buffer, sizeof buffer, stdin)) /* error or eof */;
num_chars = strlen(buffer);
if (num_chars && (buffer[num_chars - 1] == '\n')) buffer[--num_chars] = 0;
puts(buffer); /* add a '\n' to output */

(, 42 ), num_chars, fgets strlen .

+1

C89 ( - C99), :

FILE *fp = fopen(argv[0], "r");
size_t len=1;
char c, *buffer=calloc(1,1);
/* handle fopen() returning NULL*/
while( c=fgetc(fp),!feof(fp) )
  if( c=='\n' )
  {
    puts(buffer);
    len=1;
    *buffer=0;
  }
  else
    strncat(buffer=realloc(buffer,++len),&c,1); /* check for NULL needed */

puts(buffer);
free(buffer);
fclose(fp);
-1
#include<stdio.h>
void main()
{
    FILE *fp;
    char c;
    int ch=0,w=0,l=0;
    fp=fopen("c:\read.txt","w");
    clrscr();
    if(fp==NULL)
    {
        printf("\n\n\tDOES NOT EXIXST");
        getch();
        exit(0);
    }
    while(!feof(fp))
    {
        c=fgetc(fp);

        ch++;
        if(c==' ')
        {
            w++;
        }
        if(c=='\n')
        {
            l++;
            w++;
        }
    }

    printf("\n\n\tTOTAL CHAR = %d\n\n\tTOTAL WORDS = %d\n\n\tTOTAL LINES = %d",ch,w,l);

}
-2

All Articles