File Pointer
A file pointer is a reference to a particular position in the opened file. It is used in file
handling to perform all file operations such as read, write, close, etc. We use the FILE macro
to declare the file pointer variable. The FILE macro is defined inside <stdio.h> header file.
FILE* pointer_name;
File Pointer is used in almost all the file operations in C.
File Operation Functions
The file operations are performed by using the functions provided as the part of file handling
API of C language. Following is the list of commonly used functions:
Open a File in C
For opening a file in C, the fopen() function is used with the filename or file path along with
the required access modes.
FILE* fopen(*file_name, *access_mode);
Parameters
file_name: name of the file when present in the same directory as the source file. Otherwise,
full path.
access_mode: Specifies for what operation the file is being opened.
Example:
#include <stdio.h>
#include <stdlib.h>
int main()
FILE* fptr;
fptr = fopen("filename.txt", "r");
if (fptr == NULL) {
printf("The file is not opened.");
}
else{
printf("The file is opened.");
}
return 0;
}
The fopen() function is also capable of creating a file if it does not exist.
Create a File in C
The fopen() function can not only open a file but also can create a file if it does not exist
already. For that, we have to use the modes that allow the creation of a file if not found such
as w, w+, wb, wb+, a, a+, ab, and ab+.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE* fptr;
fptr = fopen("file.txt", "w");
if (fptr == NULL)
printf("The file is not opened.");
else
printf("The file is created Successfully.");
return 0;
}
Write to a File
The file write operations can be performed by the functions fprintf() and fputs(). C
programming also provides some other functions that can be used to write data to a file
such as:
}
Example:
#include <stdio.h>
#include <stdlib.h>
int main() {
// File pointer
FILE* fptr;
// Get the data to be written in file
char data[50] = "GeeksforGeeks-A Computer "
"Science Portal for Geeks";
// Creating file using fopen()
// with access mode "w"
fptr = fopen("file.txt", "w");
// Checking if the file is created
if (fptr == NULL)
printf("The file is not opened.");
else{
printf("The file is now opened.\n");
fputs(data, fptr);
fputs("\n", fptr);
// Closing the file using fclose()
fclose(fptr);
printf("Data successfully written in file "
"file.txt\n");
printf("The file is now closed.");
}
return 0;
}
Reading From a File
The file read operation in C can be performed using functions fscanf() or fgets(). Both the
functions performed the same operations as that of scanf() and gets but with an additional
parameter, the file pointer. There are also other functions we can use to read from a file. Such
functions are listed below:
Example:
#include <stdio.h>
#include <string.h>
int main() {
FILE* fptr;
// Declare the character array
// for the data to be read from file
char data[50];
fptr = fopen("file.txt", "r");
if (fptr == NULL) {
printf("file.txt file failed to open.");
}
else {
printf("The file is now opened.\n");
// Read the data from the file
// using fgets() method
while (fgets(data, 50, fptr)
!= NULL) {
// Print the data
printf("%s", data);
}
// Closing the file using fclose()
fclose(fptr);
}
return 0;
}
Read using fgetc():
#include <stdio.h>
int main() {
FILE* fptr;
char ch;
fptr = fopen("file.txt", "r");
if (fptr == NULL) {
printf("file.txt failed to open.\n");
} else {
printf("The file is now opened.\n");
// Read the file character by character
while ((ch = fgetc(fptr)) != EOF) {
printf("%c", ch);
}
fclose(fptr);
printf("\nThe file is now closed.\n");
}
return 0;
}
C Program to Merge Contents of Two Files into a Third File
#include <stdio.h>
int main() {
// Open the source files in read mode and the destination file in write mode
FILE *fptr1 = fopen("file1.txt", "r");
FILE *fptr2 = fopen("file2.txt", "r");
FILE *fptr3 = fopen("merged.txt", "w");
// Check if the files were opened successfully
if (fptr1 == NULL || fptr2 == NULL || fptr3 == NULL) {
printf("Error opening files!\n");
return 1;
}
// Copy contents of the first file to the third file
char ch;
while ((ch = fgetc(fptr1)) != EOF) {
fputc(ch, fptr3);
}
// Copy contents of the second file to the third file
while ((ch = fgetc(fptr2)) != EOF) {
fputc(ch, fptr3);
}
fclose(fptr1);
fclose(fptr2);
fclose(fptr3);
printf("Contents merged successfully");
return 0;
}
Append Data to a File
#include <stdio.h>
int main() {
FILE *fptr = fopen("sample.txt", "a");
if(fptr == NULL) {
printf("Cannot open file.\n");
return 1;
}
fprintf(fptr, "This line is appended.\n");
fclose(fptr);
printf("Data appended successfully.\n");
return 0;
}
Count Number of Characters in a File
#include <stdio.h>
int main() {
FILE *fptr = fopen("sample.txt", "r");
char ch;
int count = 0;
if(fptr == NULL) {
printf("File not found.\n");
return 1;
}
while((ch = fgetc(fptr)) != EOF) {
count++;
}
fclose(fptr);
printf("Total characters: %d\n", count);
return 0;
}
Copy Contents from One File to Another
#include <stdio.h>
int main() {
FILE *src = fopen("sample.txt", "r");
FILE *dest = fopen("copy.txt", "w");
char ch;
if(src == NULL || dest == NULL) {
printf("File error.\n");
return 1;
}
while((ch = fgetc(src)) != EOF) {
fputc(ch, dest);
}
fclose(src);
fclose(dest);
printf("File copied successfully.\n");
return 0;
}
Count Words in a File
#include <stdio.h>
#include <ctype.h>
int main() {
FILE *fptr = fopen("sample.txt", "r");
char ch;
int inWord = 0, words = 0;
if(fptr == NULL) {
printf("File not found.\n");
return 1;
}
while((ch = fgetc(fptr)) != EOF) {
if(isspace(ch)) {
inWord = 0;
} else if(!inWord) {
inWord = 1;
words++;
}
}
fclose(fptr);
printf("Total words: %d\n", words);
return 0;
}
C program to count the number of times each word appears in a file,
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORDS 1000
#define WORD_LEN 50
// Convert a string to lowercase
void toLowerCase(char *str) {
for(int i=0;str[i];i++)
str[i]=tolower(str[i]);
}
// Check if two words are the same
int isSame(char *a,char *b){
return strcmp(a,b)==0;
}
int main() {
FILE *f;
char word[WORD_LEN];
char words[MAX_WORDS][WORD_LEN];
int count[MAX_WORDS]={0};
int n=0,found;
f=fopen("file.txt","r");
if(f==NULL){
printf("File not found.\n");
return 1;
}
while(fscanf(f,"%s",word)==1){
toLowerCase(word);
// Remove trailing punctuation
int len=strlen(word);
while(len>0&&ispunct(word[len-1])){
word[len-1]='\0';
len--;
}
found=0;
for(int i=0;i<n;i++){
if(isSame(words[i],word)){
count[i]++;
found=1;
break;
}
}
if(!found){
strcpy(words[n],word);
count[n]=1;
n++;
}
}
fclose(f);
printf("Word frequencies:\n");
for(int i=0;i<n;i++){
printf("%s: %d\n",words[i],count[i]);
}
return 0;
}
WORD FREQUENCY COUNTER FROM FILE
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORDS 100
#define MAX_LEN 20
int main() {
FILE *fp = fopen("input.txt", "r");
if (fp == NULL) {
printf("File not found.\n");
return 1;
}
char words[MAX_WORDS][MAX_LEN];
int count[MAX_WORDS];
int total = 0;
char word[MAX_LEN];
int i, j, k = 0;
char c;
while ((c = fgetc(fp)) != EOF) {
if (isalnum(c)) {
word[k++] = tolower(c);
} else if (k > 0) {
word[k] = '\0';
k = 0;
int found = 0;
for (i = 0; i < total; i++) {
if (strcmp(words[i], word) == 0) {
count[i]++;
found = 1;
break;
}
}
if (!found && total < MAX_WORDS) {
strcpy(words[total], word);
count[total] = 1;
total++;
}
}
}
if (k > 0) {
word[k] = '\0';
int found = 0;
for (i = 0; i < total; i++) {
if (strcmp(words[i], word) == 0) {
count[i]++;
found = 1;
break;
}
}
if (!found && total < MAX_WORDS) {
strcpy(words[total], word);
count[total] = 1;
total++;
}
}
fclose(fp);
for (i = 0; i < total - 1; i++) {
for (j = i + 1; j < total; j++) {
if (count[i] < count[j]) {
int temp = count[i];
count[i] = count[j];
count[j] = temp;
char tempWord[MAX_LEN];
strcpy(tempWord, words[i]);
strcpy(words[i], words[j]);
strcpy(words[j], tempWord);
}
}
}
printf("Word Frequency (Descending Order):\n");
for (i = 0; i < total; i++) {
printf("%s: %d\n", words[i], count[i]);
}
return 0;
}
Example:
Increment Numeric Words and Replace in Same File
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int isNumeric(char *word) {
for (int i = 0; word[i]; i++) {
if (!isdigit(word[i])) return 0;
}
return 1;
}
int main() {
FILE *fp = fopen("file.txt", "r");
if (fp == NULL) {
printf("Unable to open file.\n");
return 1;
}
char content[1000] = "";
char word[100];
// Read words and process
while (fscanf(fp, "%s", word) != EOF) {
if (isNumeric(word)) {
int num = atoi(word);
num++;
char temp[20];
sprintf(temp, "%d", num);
strcat(content, temp);
} else {
strcat(content, word);
}
strcat(content, " ");
}
fclose(fp);
// Write back to same file
fp = fopen("file.txt", "w");
if (fp == NULL) {
printf("Unable to open file for writing.\n");
return 1;
}
// Remove trailing space
int len = strlen(content);
if (len > 0 && content[len - 1] == ' ') content[len - 1] = '\0';
fputs(content, fp);
fclose(fp);
printf("File updated successfully.\n");
return 0;
}