How do I get fgetc to print all the characters of a file inside of a loop

user798774 picture user798774 · Jul 8, 2011 · Viewed 8.2k times · Source

I'm playing around with fgetc and was wondering how I would get my loop to print the line section once then print the first 16 characters.

Here is my code:

int main(int argc, char * argv[])
{
    FILE *fp;

    if((fp = fopen(argv[1], "rb+")) == '\0')
    {
        perror("fopen");
        return 0;
    }

    getchar(fp);

    return 0;
}

void getchar(FILE *fp)
{
    int c;
    size_t linecount = 0;

    while((c = fgetc(fp)) != EOF)
    {
        printf("line : ");
        printf("%c ", c);
        linecount++;

        if(linecount == 16)
        {
            printf("\n");
        }
    }
}

I want my output to be something like:

 line: ? 5 d s d a d 0 0 0 0 0 0 0 0 0 0 0
 line: a d s x c v d 0 0 0 0 0 0 0 0

I've tried printing the characters using this for loop:

for(i = 0; i < 16; i++)
{
   printf("%c ", c);
}

But that didn't get the other characters, because the loop was still concentrated on the first character

Answer

caf picture caf · Jul 8, 2011

Firstly, there is already a standard function called getchar() defined in <stdio.h> - you must change the name of your function, or your may get some very strange behaviour.

Secondly, it seems to me that what you want to do is:

  • Print out "line: ";
  • Read a character and print it, until end of file or you have printed 16 characters;
  • Print out "\n".

This would translate into code form as:

printf("line : ");

while (linecount < 16 && (c = fgetc(fp)) != EOF)
{
    printf("%c ", c);
    linecount++;
}

printf("\n");