C - File I/O: Opening Files
C - File I/O: Opening Files
C - File I/O: Opening Files
C - File I/O
A file represents a sequence of bytes on the disk where a group of related data is
stored. File is created for permanent storage of data. It is a readymade structure.
Opening Files
You can use the fopen( ) function to create a new file or to open an
existing file. This call will initialize an object of the type FILE, which
contains all the information necessary to control the stream. The
prototype of this function call is as follows −
FILE *fopen( const char * filename, const char * mode );
Here, filename is a string literal, which you will use to name your file,
and access mode can have one of the following values −
1
R
2 W
Opens a text file for writing. If it does not exist, then a new file is
created. Here your program will start writing content from the beginning
of the file.
3
A
Opens a text file for writing in appending mode. If it does not exist, then
a new file is created. Here your program will start appending content in
the existing file content.
4 r+
5
w+
Opens a text file for both reading and writing. It first truncates the file to
zero length if it exists, otherwise creates a file if it does not exist.
6 a+
Opens a text file for both reading and writing. It creates the file if it does
not exist. The reading will start from the beginning but writing can only
be appended.
If you are going to handle binary files, then you will use following access
modes instead of the above mentioned ones −
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+b", "ab+", "a+b"
Closing a File
To close a file, use the fclose( ) function. The prototype of this function is
−
int fclose( FILE *fp );
Writing a File
Following is the simplest function to write individual characters to a
stream −
int fputc( int c, FILE *fp );
#include <stdio.h>
main() {
FILE *fp;
fp = fopen("Balu/test.txt", "w+");
fclose(fp);
Reading a File
Given below is the simplest function to read a single character from a file
−
int fgetc( FILE * fp );
If this function encounters a newline character '\n' or the end of the file
EOF before they have read the maximum number of characters, then it
returns only the characters read up to that point including the new line
character. You can also use int fscanf(FILE *fp, const char
*format, ...) function to read strings from a file, but it stops reading
after encountering the first space character.
#include <stdio.h>
main() {
FILE *fp;
char buff[255];
fp = fopen("/tmp/test.txt", "r");
fclose(fp);
When the above code is compiled and executed, it reads the file created
in the previous section and produces the following result −
1 : This
2: is testing for fprintf...
File Input/Output in C
A file represents a sequence of bytes on the disk where a group of related data is
stored. File is created for permanent storage of data. It is a ready made structure.
In C language, we use a structure pointer of file type to declare a file.
FILE *fp;
C provides a number of functions that helps to perform basic file operations. Following
are the functions,
Function description
mode description
Closing a File
The fclose() function is used to close an already opened file.
General Syntax :
int fclose( FILE *fp);
Here fclose() function closes the file and returns zero on success, or EOF if there is an
error in closing the file. This EOF is a constant defined in the header file stdio.h.
int main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch = getchar()) != EOF) {
putc(ch, fp);
}
fclose(fp);
fp = fopen("one.txt", "r");
return 0;
}
struct emp
{
char name[10];
int age;
};
void main()
{
struct emp e;
FILE *p,*q;
p = fopen("one.txt", "a");
q = fopen("one.txt", "r");
printf("Enter Name and Age:");
scanf("%s %d", e.name, &e.age);
fprintf(p,"%s %d", e.name, e.age);
fclose(p);
do
{
fscanf(q,"%s %d", e.name, e.age);
9| Institute of Professional Computer Programming & Designing, Contact 95027 83007
Indian Bank Road, Veerabhdra Swamy temple Backside, Bhimavaram - 1, W. G Dist., A.P.
Vikram Computer Institute C Language
LEARN HOW TO THINK & THINK HOW TO DEVELOP
fseek(), ftell() and rewind() functions
fseek(): It is used to move the reading control to different positions using fseek
function.
ftell(): It tells the byte location of current position of cursor in file pointer.
C fseek() function
The fseek() function is used to set the file pointer to the specified offset. It is used to
write data into file at desired location.
Syntax:
1. int fseek(FILE *stream, long int offset, int whence)
There are 3 constants used in the fseek() function for whence: SEEK_SET, SEEK_CUR
and SEEK_END.
Example:
1. #include <stdio.h>
2. void main(){
3. FILE *fp;
4.
5. fp = fopen("myfile.txt","w+");
6. fputs("This is javatpoint", fp);
7.
8. fseek( fp, 7, SEEK_SET );
9. fputs("sonoo jaiswal", fp);
10. fclose(fp);
11. }
myfile.txt
C rewind() function
The rewind() function sets the file pointer at the beginning of the stream. It is useful if
you have to use stream many times.
Syntax:
1. void rewind(FILE *stream)
Example:
File: file.txt
1. this is a simple text
File: rewind.c
1. #include<stdio.h>
2. #include<conio.h>
3. void main(){
4. FILE *fp;
5. char c;
6. clrscr();
7. fp=fopen("file.txt","r");
8.
9. while((c=fgetc(fp))!=EOF){
10. printf("%c",c);
11. }
12.
13. rewind(fp);//moves the file pointer at beginning of the file
14.
15. while((c=fgetc(fp))!=EOF){
16. printf("%c",c);
17. }
18.
19. fclose(fp);
20. getch();
21. }
Output:
As you can see, rewind() function moves the file pointer at beginning of the file that is
why "this is simple text" is printed 2 times. If you don't call rewind() function, "this is
simple text" will be printed only once.
C ftell() function
The ftell() function returns the current file position of the specified stream. We can use
ftell() function to get the total size of a file after moving file pointer at the end of file. We
can use SEEK_END constant to move the file pointer at the end of file.
Syntax:
1. long int ftell(FILE *stream)
Example:
File: ftell.c
1. #include <stdio.h>
2. #include <conio.h>
3. void main (){
4. FILE *fp;
5. int length;
6. clrscr();
7. fp = fopen("file.txt", "r");
8. fseek(fp, 0, SEEK_END);
9.
10. length = ftell(fp);
11.
12. fclose(fp);
13. printf("Size of file: %d bytes", length);
14. getch();
15. }
Output:
1. #include<stdio.h>
2. #define start main
3. void start() {
4. printf("Hello");
5. }
Output:
Hello