Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is the FILE keyword in C?

Tags:

c

file

stdio

I've started learning some C as a hobby and have blindly used FILE as a declaration for file pointers for quite some time, and I've been wondering. Is this a keyword or special data type for C to handle files with? Does it contain a stream to the file within and other data? Why is it defined as a pointer?

An example to show what I mean to make it a little more clear:

FILE* fp; //<-- this fp = fopen("datum.txt", "r");  while(!feof(fp)) {    // etc. } 
like image 819
johnholtsdater Avatar asked Apr 15 '11 05:04

johnholtsdater


People also ask

What is the file keyword in C?

(A) FILE is a keyword in C for representing files and fp is a variable of FILE type. (B) FILE is a structure and fp is a pointer to the structure of FILE type.

What is file keyword?

It's not a keyword, it's a data type defined in the ANSI C standard to operate with files.

Where is file defined in C?

Nowadays, it's a typedef , defined in stdio. h . On macOS, in /usr/include/stdio.

How does file work in C?

For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. For Example: FILE *fp; To open a file you need to use the fopen function, which returns a FILE pointer.


1 Answers

is this a keyword or special data type for C to handle files with?

What you are refering to is a typedef'd structure used by the standard io library to hold the appropriate data for use of fopen, and its family of functions.

Why is it defined as a pointer?

With a pointer to a struct, you can then pass it as a parameter to a function. This is for example what fgets or fgetc will accept, in the form of function(FILE* fp)

The fopen function will return a pointer to a newly created FILE struct, assigning this new pointer to your unused one will cause them to point to the same thing.

Does it contain a stream to the file within and other data?

The structure definition seems a little more illusive than its description. This is directly taken from my stdio.h, from MinGW32 5.1.4

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

Which includes the lovely comment before it:

Some believe that nobody in their right mind should make use of the internals of this structure.

The contents of this structure appear to change greatly on other implementations, the glibc sources usually have some form of commenting but their structure for this is burried under a lot of code.

It would make sense to heed the aforementioned warning and just not worry what it does. :)

like image 89
Alexander Avatar answered Sep 29 '22 12:09

Alexander