0

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.

Edited by myk45: n/a

2
Contributors
2
Replies
4
Views
6 Years
Discussion Span
Last Post by myk45
1

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.

Votes + Comments
Thanks!
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.