C - File I/O: Opening Files

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Vikram Computer Institute C Language

LEARN HOW TO THINK & THINK HOW TO DEVELOP

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.

It may be a text file or a binary file.


In C language, we use a structure pointer of file type to declare a file.
Syntax: FILE *fp;

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 −

Sr.No Mode & Description


.

1
R

Opens an existing text file for reading purpose.

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+

1| 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

Opens a text file for both reading and writing.

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 );

The fclose(-) function returns zero on success, or EOF if there is an


error in closing the file. This function actually flushes any data still
pending in the buffer to the file, closes the file, and releases any memory
used for the file. The EOF is a constant defined in the header file stdio.h.

There are various functions provided by C standard library to read and


write a file, character by character, or in the form of a fixed length
string.

Writing a File
Following is the simplest function to write individual characters to a
stream −
int fputc( int c, FILE *fp );

The function fputc() writes the character value of the argument c to the


output stream referenced by fp. It returns the written character written
on success otherwise EOF if there is an error. You can use the following
functions to write a null-terminated string to a stream −
2| 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

int fputs( const char *s, FILE *fp );

The function fputs() writes the string s to the output stream referenced


by fp. It returns a non-negative value on success, otherwise EOF is
returned in case of any error. You can use int fprintf(FILE *fp,const
char *format, ...)function as well to write a string into a file. Try the
following example.

Make sure you have /tmp directory available. If it is not, then before


proceeding, you must create this directory on your machine.

#include <stdio.h>

main() {

FILE *fp;

fp = fopen("Balu/test.txt", "w+");

fprintf(fp, "This is testing for fprintf...\n");

fputs("This is testing for fputs...\n", fp);

fclose(fp);

When the above code is compiled and executed, it creates a new


file test.txtin /tmp directory and writes two lines using two different
functions. Let us read this file in the next section.

Reading a File
Given below is the simplest function to read a single character from a file

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file referenced by


fp. The return value is the character read, or in case of any error, it
returns EOF. The following function allows to read a string from a stream

char *fgets( char *buf, int n, FILE *fp );

3| 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

The functions fgets() reads up to n-1 characters from the input stream


referenced by fp. It copies the read string into the buffer buf, appending
a null character to terminate the string.

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");

fscanf(fp, "%s", buff);

printf("1 : %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("2: %s\n", buff );

fgets(buff, 255, (FILE*)fp);

printf("3: %s\n", buff );

fclose(fp);

When the above code is compiled and executed, it reads the file created
in the previous section and produces the following result −

4| 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

1 : This
2: is testing for fprintf...

3: This is testing for fputs...

Let's see a little more in detail about what happened here.


First, fscanf() read just This because after that, it encountered a space,
second call is for fgets()which reads the remaining line till it
encountered end of line. Finally, the last call fgets() reads the second
line completely.

Binary I/O Functions


There are two functions, that can be used for binary input and output −

size_t fread(void *ptr, size_t size_of_elements, size_t number_of_elements, FILE


*a_file);

size_t fwrite(const void *ptr, size_t size_of_elements, size_t number_of_elements,


FILE *a_file);

Both of these functions should be used to read or write blocks of


memories - usually arrays or structures.

5| 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

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

fopen() create a new file or open a existing file

fclose() closes a file

getc() reads a character from a file

putc() writes a character to a file

fscanf() reads a set of data from a file

fprintf() writes a set of data to a file

getw() reads a integer from a file

putw() writes a integer to a file

6| 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() set the position to desire point

ftell() gives current position in the file

rewind() set the position to the begining point

Opening a File or Creating a File


The fopen() function is used to create a new file or to open an existing file.
General Syntax:
*fp = FILE *fopen(const char *filename, const char *mode);
Here, *fp is the FILE pointer (FILE *fp), which will hold the reference to the opened(or
created) file.
filename is the name of the file to be opened and mode specifies the purpose of
opening the file. Mode can be of following types,

mode description

r opens a text file in reading mode

w opens or create a text file in writing mode.

a opens a text file in append mode

r+ opens a text file in both reading and writing mode

w+ opens a text file in both reading and writing mode

a+ opens a text file in both reading and writing mode

rb opens a binary file in reading mode

7| 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

wb opens or create a binary file in writing mode

ab opens a binary file in append mode

rb+ opens a binary file in both reading and writing mode

wb+ opens a binary file in both reading and writing mode

ab+ opens a binary file in both reading and writing mode

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.

Input/Output operation on File


In the above table we have discussed about various file I/O functions to perform reading
and writing on file. getc() and putc() are the simplest functions which can be used to
read and write individual characters to a file.
#include<stdio.h>

int main()
{
FILE *fp;
char ch;
fp = fopen("one.txt", "w");
printf("Enter data...");
while( (ch = getchar()) != EOF) {
putc(ch, fp);

8| 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

}
fclose(fp);
fp = fopen("one.txt", "r");

while( (ch = getc(fp)! = EOF)


printf("%c",ch);

// closing the file pointer


fclose(fp);

return 0;
}

Reading and Writing to File


using fprintf() and fscanf()
#include<stdio.h>

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

printf("%s %d", e.name, e.age);


}
while(!feof(q));
}
In this program, we have created two FILE pointers and both are refering to the same file
but in different modes.
fprintf() function directly writes into the file, while fscanf() reads from the file, which
can then be printed on the console using standard printf() function.

Difference between Append and Write Mode


Write (w) mode and Append (a) mode, while opening a file are almost the same. Both
are used to write in a file. In both the modes, new file is created if it doesn't exists
already.
The only difference they have is, when you open a file in the write mode, the file is
reset, resulting in deletion of any data already present in the file. While in append mode
this will not happen. Append mode is used to append or add data to the existing data of
file(if any). Hence, when you open a file in Append(a) mode, the cursor is positioned at
the end of the present data in the file.

Reading and Writing in a Binary File


A Binary file is similar to a text file, but it contains only large numerical data. The
Opening modes are mentioned in the table for opening modes above.
fread() and fwrite() functions are used to read and write is a binary file.
fwrite(data-element-to-be-written, size_of_elements, number_of_elements, pointer-
to-file);
fread() is also used in the same way, with the same arguments like fwrite() function.
Below mentioned is a simple example of writing into a binary file
const char *mytext = "The quick brown fox jumps over the lazy dog";
FILE *bfp= fopen("test.txt", "wb");
if (bfp)
{
fwrite(mytext, sizeof(char), strlen(mytext), bfp);
fclose(bfp);
}

10 | 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.

 rewind(): It moves the control to beginning of the file.

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

This is sonoo jaiswal

C rewind() function

11 | 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

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:

this is a simple textthis is a simple text

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.

12 | 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

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:

Size of file: 21 bytes

C Program without main() function


We can write c program without using main() function. To do so, we need to use #define
preprocessor directive.

Let's see a simple program to print "hello" without main() function.

1. #include<stdio.h>    
2.  #define start main    
3. void start() {    
4.    printf("Hello");    
5. }   

13 | 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

Output:

Hello

14 | Institute of Professional Computer Programming & Designing, Contact 95027 83007


Indian Bank Road, Veerabhdra Swamy temple Backside, Bhimavaram - 1, W. G Dist., A.P.

You might also like