C Tutorial
File pointer is actually a pointer to a structure, structure has been typedefed into FILE in the header file 'stdio.h'.
File pointer syntax,
FILE *<file-poiner1>, *<file-poiner2>, ...;
FILE structure,
typedef struct { // fill/empty level of buffer int level; // File status flags unsigned flags; // File descripter char fd; // ungetc char if no buffer unsigned char hold; // buffer size int bsize; // data transfer buffer unsigned char *buffer; // Current active pointer unsigned char *curp; //Temporary file indicator unsigned istemp; //Used for validity checking short token; } FILE; // This is FILE object
Following steps happens when open a file using file pointer,
The content of the file are loaded into buffer.
A FILE structure is created in memory, address of this structure us returned once elements are assigned.
This c program shows how to use thefile pointers to read the number of characters in the input file.
Program opens a file, reads it character by character till the time its end is not encountered. On reaching tthe end of file 'EOF', the file is closed and prints the total number of characters in the file.
fp is the file pointer in the program.
#include<stdio.h> void main() { FILE *fp; char ch; int noc = 0; fp = fopen("test.txt", "r"); while(1) { ch = fgetc(fp); if(ch == EOF) { break; } noc++; } fclose(fp); printf("\nNumber of characters in file: %d", noc); }
Let us consider the input text.txt file content is,
$ cat test.txt Welcome to codingpointer.com!
Output:
$ cc file-pointer.c $ ./a.out Number of characters in file: 30
Another example to read the file content along with number of characters using FILE pointer,
#include<stdio.h> void main() { FILE *fp; char ch; int noc = 0; fp = fopen("test.txt", "r"); printf("File content: \n"); while(1) { ch = fgetc(fp); if(ch == EOF) { break; } printf("%c", ch); noc++; } fclose(fp); printf("\nNumber of characters in file: %d", noc); }
Let us consider the input text.txt file content is,
$ cat test.txt Welcome to codingpointer.com!
Output:
$ cc file-pointer.c $ ./a.out File content: Welcome to codingpointer.com! Number of characters in file: 30
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page