0% found this document useful (0 votes)
12 views8 pages

Module 5 - Files

vtu notes

Uploaded by

savagegamer1289
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
12 views8 pages

Module 5 - Files

vtu notes

Uploaded by

savagegamer1289
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 8

FILES

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 a 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. You can easily create text files using any simple text editors
such as Notepad.

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 the 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 a higher amount of data, are not readable easily, and provides better security than
text files.
File Operations
In C, you can perform four major operations on files, 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

Defining and Opening File(fopen( ))


 C provides a data type to work with files i.e. FILE. We need to create pointer of
FILE type before opening file.
 Function used create/open file is fopen(). This function on successful execution
returns a pointer to the opened file.
 fopen() takes two parameters, 1. The filename 2. The mode in which file is to
opened(more about it later)
 E.g.: FILE *fp; fp = fopen(“file name”, “mode”);
 On success, fopen() returns the address of the file opened(call it as file handle)we
store it in a FILE type pointer fp. Now fp represents our file handle. Any further
operation we want to perform on the opened file requires this file handle.
 On failure fopen() returns NULL.
Parameters of fopen()
1. File name :
 The name of the file to be created/opened. Remember we will want to create a file if
it is not already existing. Otherwise we will want to open the existing file. For both,
fopen() is the function.
 Normally file name consists of the name part and an extension( e.g. hello.txt).
Extension is optional normally.

2. Mode:
 mode specifies the purpose of opening the file.
File Opening Description
Modes
r Opens an existing text file for reading purpose.If the file is opened successfully
fopen( ) loads it into memory and sets up a pointer that points to the first character
in it. If the file cannot be opened fopen( ) returns NULL.
rb Open for reading in binary mode. If the file does not exist, fopen( ) returns NULL.
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.
wb Open for writing in binary mode. If the file exists, its contents are overwritten. If
the file does not exist, it will be created.
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 by pointing to the last character in it.
ab Open for append in binary mode. Data is added to the end of the file. If the file does
not exist, it will be created.
r+ Open a text file for both reading and writing. It specify that it want to read the file
before something is written to it. File must already exist.
rb+ Open for both reading and writing in binary mode. If the file does not exist, fopen(
) returns NULL.
w+ Searches file. If the file exists, its contents are overwritten. If the file doesn’t exist a
new file is created. Returns NULL, if unable to open the file.
wb+ Open for both reading and writing in binary mode. If the file exists, its contents are
overwritten. If the file does not exist, it will be created.
a+ 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. If the file doesn’t exist, a new
file is created. Returns NULL, if unable to open the file.
aw+ Open for both reading and appending in binary mode. If the file does not exist, it
will be created.

Closing a file (fclose())


 After we are finished with all operations, we are expected to close the file. fclose
() is the function/ for this. It takes file handle as the parameter.
 General form : flclose(file_pointer);

E.g.: fclose(p1); fclose(p2);


C provides a number of functions that helps to perform basic file operations.
Following are the functions.

Reading a file
Functions Syntax Description
int fscanf (FILE *stream, const It is used for reading the
fscanf( )
char *format,....); formatted data from the stream.
It stands for file get string. It is
char *fgets(char *str, int size,
fgets( ) used for getting the string from a
FILE *stream);
stream.
It will return the next character
fgetc( ) int fgetc (FILE *stream); from the stream from the end of
the file or an error.
int fread(void *str, size_t size, It is used for reading data from a
fread( )
size_t num, FILE *stream); file.

Writing a file
Functions Syntax Description
int fprintf (FILE *stream, const It is used for writing the
fprintf()
char * format,...); formatted output of the stream.
int fputs(const char *str, FILE It is used for writing a line to a
fputs()
*stream); file.
It is opposite to fgetc() and is
fputc() int fputc(int c, FILE *stream); used for writing a character to the
stream.
int fwrite(const void *str, size_t It is used for writing data to a
fwrite()
size, size_t count, file *stream); file.

1)Example for reading an integer number from text file

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

int main()
{
int num;
FILE *fptr;

if ((fptr = fopen("file.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;
}

1)Example for reading a string number from text file


#include <stdio.h>
int main(){
FILE *fp;
char buff[255];//creating char array to store data of file
fp = fopen("file.txt", "r");
while(fscanf(fp, "%s", buff)!=EOF){
printf("%s ", buff );
}
fclose(fp);
return 0;
}

3)Example for writing an integer number into text file


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

int main()
{
int num;
FILE *fptr;

// use appropriate location if you are using MacOS or Linux


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

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

printf("Enter num: ");


scanf("%d",&num);

fprintf(fptr,"%d",num);
fclose(fptr);

return 0;
}
4)Example for writing a string into text file
#include <stdio.h>
int main(){
FILE *fp;
fp = fopen("file.txt", "w");//opening file
fprintf(fp, "Hello file ..\n");//writing data into file
fclose(fp);//closing file
return 0;
}

5)Example for appending a string to a text file

#include <stdio.h>

int main() {
FILE *fptr;

// Open a file in append mode


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

// Append some text to the file


fprintf(fptr, "Hi everybody!");

// Close the file


fclose(fptr);

return 0;
}
6)Example for fputs and fgets

#include<stdio.h>

void main(){
FILE *fp;

fp=fopen("file.txt","w");
fputs("hello c programming",fp);

fclose(fp);

}
7)Example for fputs and fgets

#include <stdio.h>
int main() {
FILE *fp, *fw; // file pointers for the respective read and write mode.
char s[30];
fp = fopen("Doc1.txt", "r"); // The file that contains the String
fw = fopen("Doc2.txt","w"); // The file from which the string is being copied
/*while runs until it gets NULL*/
while (fgets(s,30,fp) != NULL)
{
fputs(s, fw); // copying to the file Doc2.txt
printf("%s", s);
}
fclose(fp);
fclose(fw);
return 0;
}

6)Example for fread

#include <stdio.h>

int main()
{
FILE *fp;
char arr[50];
fp=fopen("xyz.txt","r");
fread(arr,1,50,p);
printf("%s",arr);
fclose(p);
return 0;
}
6)Example for fwrite

#include <stdio.h>

int main()
{
FILE *fp;
int arr[]={97,98,99,100,101};
fp=fopen("xyz.txt","w");
if(p!=NULL)
{
fwrite(&arr,4,5,p);
}
fclose(p);
return 0;
}

You might also like