Pelles C forum

C language => Beginner questions => Topic started by: kapokia on January 22, 2013, 06:33:36 AM

Title: what's wrong with the file pointer?
Post by: kapokia on January 22, 2013, 06:33:36 AM
The two pieces of codes seemed as the same, but the output results are different.

This one goes correctly:
#include <stdio.h>

main()
{
FILE *fp = fopen("test.txt", "rb");
unsigned char buf[4];
while (fread(buf, 1, 1, fp))
{
printf("%s", buf);
memset(buf, 0, 1);
}
}


This one is incorrect:
#include <stdio.h>

void read(FILE *fp)
{
unsigned char buf[4];
while (fread(buf, 1, 1, fp))
{
printf("%s", buf);
memset(buf, 0, 1);
}
}

main()
{
FILE *fp = fopen("test.txt", "rb");
read(fp);
}


What's wrong with the second one?
Title: Re: what's wrong with the file pointer?
Post by: CLR on January 22, 2013, 06:59:29 AM
Uninitialized buffer?
Title: Re: what's wrong with the file pointer?
Post by: kapokia on January 22, 2013, 07:03:52 AM
Quote from: CLR on January 22, 2013, 06:59:29 AM
Uninitialized buffer?
Neither the first one nor the second one initialized.
Both compiled and runnable, but the output result of the second one is wrong.
Title: Re: what's wrong with the file pointer?
Post by: woody on January 22, 2013, 11:40:18 AM
You should always memset a local buffer before any operation and you should do it complete. Not just the first element.
And it is good practice to prototype your read(). There are more functions with that name but but different arguments.
So the reason is a garbage on the stack that must be cleared.
This should work:

#include <stdio.h>

void read(FILE *fp);

void read(FILE *fp)
{
    unsigned char buf[4];
    memset(buf, 0, sizeof buf);
    while (fread(buf, 1, 1, fp))
    {
        printf("%s", buf);
    }
}

main()
{
    FILE *fp = fopen("test.txt", "rb");
    read(fp);
}


Woody
Title: Re: what's wrong with the file pointer?
Post by: kapokia on January 22, 2013, 11:59:53 AM
Quote from: woody on January 22, 2013, 11:40:18 AM
You should always memset a local buffer before any operation and you should do it complete. Not just the first element.
And it is good practice to prototype your read(). There are more functions with that name but but different arguments.
So the reason is a garbage on the stack that must be cleared.
This should work:

#include <stdio.h>

void read(FILE *fp);

void read(FILE *fp)
{
    unsigned char buf[4];
    memset(buf, 0, sizeof buf);
    while (fread(buf, 1, 1, fp))
    {
        printf("%s", buf);
    }
}

main()
{
    FILE *fp = fopen("test.txt", "rb");
    read(fp);
}

Woody
Thanks a lot. It works correctly.