Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a FILE pointer in C work?

Tags:

c

file

If we write:

//in main

FILE *p = fopen("filename", "anymode");

My question is: to what is p pointing?

like image 785
OldSchool Avatar asked Mar 05 '14 01:03

OldSchool


People also ask

What does file * fp mean in C?

In C, we use a structure pointer of a file type to declare a file: FILE *fp; C provides a number of build-in function to perform basic file operations: fopen() - create a new file or open a existing file. fclose() - close a file.

Why is a file declared as a pointer?

Declaring a File Pointer A file pointer is a pointer variable that specifies the next byte to be read or written to. Every time a file is opened, the file pointer points to the beginning of the file.

What is a pointer file?

A "pointer" file has the . MDC extension and contains pointers to the tables in which the data is stored. The . MDC file is a PC based file stored in the PowerCubes directory as specified in the Preferences dialog on the PC, or as specified by the CubeSaveDirectory user preference on the server.

What is file pointer syntax?

General Syntax:*fp = FILE *fopen(const char *filename, const char *mode); Here, *fp is the FILE pointer ( FILE *fp ), which will hold the reference to the opened(or created) file. filename is the name of the file to be opened and mode specifies the purpose of opening the file.


2 Answers

The file pointer p is pointing a structure handled by the C library that manages I/O functionality for the named file in the given open mode.

You can't tell, a priori, whether what it points at is statically allocated memory or dynamically allocated memory; you don't need to know. You treat it as an opaque pointer.

Note that the standard says:

ISO/IEC 9899:2011 7.21.3 Files

The address of the FILE object used to control a stream may be significant; a copy of a FILE object need not serve in place of the original.

This says (roughly): Don't futz around with the pointer; pass it to the functions that need it and otherwise leave well alone.

like image 62
Jonathan Leffler Avatar answered Sep 22 '22 13:09

Jonathan Leffler


p points to a memory location holding a FILE structure. That's all you really need to know, the contents of that structure are entirely implementation-specific.

If it's implemented correctly in terms of encapsulation (i.e., as an opaque structure), you shouldn't even be able to find out what it contains.

All you should be doing with it (unless you're the implementer of the standard library) is receive it from fopen and pass it to other functions requiring a FILE *, such as fwrite, fread and fclose.

like image 33
paxdiablo Avatar answered Sep 21 '22 13:09

paxdiablo