NO

Author Topic: what's wrong with the file pointer?  (Read 3636 times)

kapokia

  • Guest
what's wrong with the file pointer?
« 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:
Code: [Select]
#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:
Code: [Select]
#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?

CLR

  • Guest
Re: what's wrong with the file pointer?
« Reply #1 on: January 22, 2013, 06:59:29 AM »
Uninitialized buffer?

kapokia

  • Guest
Re: what's wrong with the file pointer?
« Reply #2 on: January 22, 2013, 07:03:52 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.

woody

  • Guest
Re: what's wrong with the file pointer?
« Reply #3 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:

Code: [Select]
#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
« Last Edit: January 23, 2013, 02:39:59 AM by Stefan Pendl »

kapokia

  • Guest
Re: what's wrong with the file pointer?
« Reply #4 on: January 22, 2013, 11:59:53 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.