0% found this document useful (0 votes)
2 views10 pages

File in C Programming: Why Files Are Needed?

The document explains the importance of files in C programming, highlighting their role in data preservation, ease of data entry, and portability. It outlines two types of files: text files, which are easily readable but less secure, and binary files, which offer better security and storage efficiency. Additionally, it details file operations such as creating, opening, closing, reading, and writing files, along with examples of file handling in C.

Uploaded by

saditlopez143
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views10 pages

File in C Programming: Why Files Are Needed?

The document explains the importance of files in C programming, highlighting their role in data preservation, ease of data entry, and portability. It outlines two types of files: text files, which are easily readable but less secure, and binary files, which offer better security and storage efficiency. Additionally, it details file operations such as creating, opening, closing, reading, and writing files, along with examples of file handling in C.

Uploaded by

saditlopez143
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

File in C Programming

Why files are needed?


 When a program is terminated, the entire data is lost. Storing in a file will preserve your data even if
the program terminates.
 If you have to enter a large number of data, it will take a lot of time to enter them all.
However, if you have a file containing all the data, you can easily access the contents of the file using
few commands in C.
 You can easily move your data from one computer to another without any changes.

Types of Files
When dealing with files, there are two types of files you should know about:

1. Text files
2. Binary files

1. Text files

Text files are the normal .txt files that you can easily create using Notepad or any simple text editors.

When you open those files, you'll see all the contents within the file as plain text. You can easily edit or delete
the contents.

They take minimum effort to maintain, are easily readable, and provide least security and takes bigger storage
space.

2. Binary files

Binary files are mostly the .bin files in your computer.

Instead of storing data in plain text, they store it in the binary form (0's and 1's).

They can hold higher amount of data, are not readable easily and provides a better security than text files.

File Operations
In C, you can perform four major operations on the file, either text or binary:

1. Creating a new file


2. Opening an existing file
3. Closing a file
4. Reading from and writing information to a file

FILE in C programming Page 1


Working with files
When working with files, you need to declare a pointer of type file. This declaration is needed for
communication between the file and program.

FILE *fptr;

Opening a file - for creation and edit


Opening a file is performed using the library function in the "stdio.h" header file: fopen().

The syntax for opening a file in standard I/O is:

ptr = fopen("fileopen","mode")

For Example:

fopen("E:\\cprogram\\newprogram.txt","w");

fopen("E:\\cprogram\\oldprogram.bin","rb");

Closing a File
The file (both text and binary) should be closed after reading/writing.

Closing a file is performed using library function fclose().

fclose(fptr); //fptr is the file pointer associated with file to be closed.

Example 1: Write to a text file using fprintf()


#include <stdio.h>
#include <stdlib.h>

int main()
{
int num;
FILE *fptr;
fptr = fopen("C:\\program.txt","w");

FILE in C programming Page 2


if(fptr == NULL)
{
printf("Error!");
exit(1);
}
printf("Enter num: ");
scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);
return 0;
}

Example 2: Read from a text file using fscanf()


#include <stdio.h>
#include <stdlib.h>
int main()
{
int num;
FILE *fptr;

if ((fptr = fopen("C:\\program.txt","r")) == NULL){


printf("Error! opening file");
// Program exits if the file pointer returns NULL.
exit(1);
}
fscanf(fptr,"%d", &num);
printf("Value of n=%d", num);
fclose(fptr);
return 0;
}

FILE in C programming Page 3


Some Examples for File handing in C
Programming

1.Write a C program to store a sentence entered by user in a file,


name “program.txt”.
#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
char sentence[1000];
FILE *fptr;

fptr = fopen("program.txt", "w");


if(fptr == NULL)
{
printf("Error!");
exit(1);
}

printf("Enter a sentence:\n");
gets(sentence);

fprintf(fptr,"%s", sentence);
fclose(fptr);
return 0;
}

Output

Enter sentence:

I am awesome and so are files.

FILE in C programming Page 4


2. Write a C program to read text from a file, name
“program.txt”.
Input file: program.txt
1 #include <stdio.h>
2#include <stdlib.h> // For exit() function C programming is
awesome.
3. int main()
4. {
I love C
5. char c[1000]; programming.
6. FILE *fptr;
7. How are you
8. if ((fptr = fopen("program.txt", "r")) == NULL) doing?

9. {
10. printf("Error! opening file");
11. // Program exits if file pointer returns NULL.
12. exit(1);
13. }
14.
15. // reads text until newline
16. fscanf(fptr,"%[^\n]", c);
17.
18. printf("Data from the file:\n%s", c);
19. fclose(fptr);
20.
21. return 0;
22. }

FILE in C programming Page 5


1. Write a C program to read name and marks of n number of students from user and store them in a
file.

#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;

printf("Enter number of students: ");


scanf("%d", &num);

FILE *fptr;
fptr = (fopen("C:\\student.txt", "w"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}

for(i = 0; i < num; ++i)


{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);

printf("Enter marks: ");


scanf("%d", &marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);


}

fclose(fptr);
return 0;
}

FILE in C programming Page 6


2. Write a C program to read name and marks of n number of students from user and store them in a
file. If the file previously exits, add the information of n students.

#include <stdio.h>
int main()
{
char name[50];
int marks, i, num;

printf("Enter number of students: ");


scanf("%d", &num);

FILE *fptr;
fptr = (fopen("C:\\student.txt", "a"));
if(fptr == NULL)
{
printf("Error!");
exit(1);
}

for(i = 0; i < num; ++i)


{
printf("For student%d\nEnter name: ", i+1);
scanf("%s", name);

printf("Enter marks: ");


scanf("%d", &marks);

fprintf(fptr,"\nName: %s \nMarks=%d \n", name, marks);


}

fclose(fptr);
return 0;
}

FILE in C programming Page 7


3. Write a C program to write all the members of an array of structures to a file using fwrite(). Read the
array from the file and display on the screen.

#include <stdio.h>
struct student
{
char name[50];
int height;
};
int main(){
struct student stud1[5], stud2[5];
FILE *fptr;
int i;

fptr = fopen("file.txt","wb");
for(i = 0; i < 5; ++i)
{
fflush(stdin);
printf("Enter name: ");
gets(stud1[i].name);

printf("Enter height: ");


scanf("%d", &stud1[i].height);
}

fwrite(stud1, sizeof(stud1), 1, fptr);


fclose(fptr);

fptr = fopen("file.txt", "rb");


fread(stud2, sizeof(stud2), 1, fptr);
for(i = 0; i < 5; ++i)
{
printf("Name: %s\nHeight: %d", stud2[i].name, stud2[i].height);
}
fclose(fptr);
}

FILE in C programming Page 8


Opening
Modes Description

Searches file. If the file is opened successfully fopen( ) loads it into


r memory and sets up a pointer that points to the first character in it.
If the file cannot be opened fopen( ) returns NULL.

Open for reading in binary mode. If the file does not exist, fopen( )
rb
returns NULL.

Open for writing in text mode. If the file exists, its contents are
w overwritten. If the file doesn’t exist, a new file is created. Returns
NULL, if unable to open the file.

Open for writing in binary mode. If the file exists, its contents are
wb
overwritten. If the file does not exist, it will be created.

Searches file. If the file is opened successfully fopen( ) loads it into


memory and sets up a pointer that points to the last character in it.
a
It opens only in the append mode. If the file doesn’t exist, a new file
is created. Returns NULL, if unable to open the file.

Open for append in binary mode. Data is added to the end of the
ab
file. If the file does not exist, it will be created.

Searches file. It is opened successfully fopen( ) loads it into memory


r+ and sets up a pointer that points to the first character in it. Returns
NULL, if unable to open the file.

Open for both reading and writing in binary mode. If the file does
rb+
not exist, fopen( ) returns NULL.

Searches file. If the file exists, its contents are overwritten. If the file
w+ doesn’t exist a new file is created. Returns NULL, if unable to open
the file.

FILE in C programming Page 9


Opening
Modes Description

Open for both reading and writing in binary mode. If the file exists,
wb+ its contents are overwritten. If the file does not exist, it will be
created.

Searches file. If the file is opened successfully fopen( ) loads it into


memory and sets up a pointer that points to the last character in it.
a+
It opens the file in both reading and append mode. If the file doesn’t
exist, a new file is created. Returns NULL, if unable to open the file.

Open for both reading and appending in binary mode. If the file does
ab+
not exist, it will be created.

FILE in C programming Page 10

You might also like