Hello,

i have a small doubt regarding the FILE structure. i looked it up in the header file (i have VC++ 2008).

In this implementation, it was declared as:

struct _iobuf {
        char *_ptr;
        int   _cnt;
        char *_base;
        int   _flag;
        int   _file;
        int   _charbuf;
        int   _bufsiz;
        char *_tmpfname;
        };
typedef struct _iobuf FILE;

here, _ptr is a the current position of the file pointer right? But im not getting the expected output in this case:

int main(void)
{
	FILE *fp;
	int c = 0; 

	if ( (fp = fopen("new.txt", "r")) == NULL ) {
		printf("\nError");
	} else {		
		while ( c != EOF ) {			
			c = fgetc(fp);        // advance pointer
			printf("%c", *(fp->_ptr));			
		}				
	}

	getchar();
	return 0;
}

Contents of new.txt: hello world
Output: ello world=h

Can anyone please explain why or how this is happening?
Thanks.

Recommended Answers

All 2 Replies

The pointer is advanced after the fgetc, so when you look at it, it is always one character ahead of what you have just read. After you have read the last character, it is pointing to garbage.

commented: Thanks! +1

Got it.Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.