0% found this document useful (0 votes)
9 views38 pages

Lec6 - Files

Uploaded by

eugeniogabriel15
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)
9 views38 pages

Lec6 - Files

Uploaded by

eugeniogabriel15
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/ 38

Unit V: FILES

Angelika S. Balagot
Instructor
Target Topics
• Topic 5.1: What are Files?
• Topic 5.2: Types of Files
• Topic 5.3: File Operations
• Topic 5.4: File Handling
- Topic 5.4.1: Create a File
- Topic 5.4.2: Closing File
- Topic 5.4.3: Write to a File
- Topic 5.4.4: Append Content to a File
- Topic 5.4.5: Reading Files
• Topic 5.5: Error Handling
• Topic 5.6: Additional Information
Topic 5.1: What are Files?
What are Files?

• A collection of data which is stored on a secondary device like


a hard disk.

• File is created for permanent storage of data.

• A file represents a sequence of bytes where a group of related data


is stored on a secondary storage devices like disk.
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.
Topic 5.2: Types of Files
Types of Files

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 read, edit or delete the contents.

• They take minimum effort to maintain, are easily readable, and


provide least security and takes bigger storage space.
Types of Files

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.
Topic 5.3: File Operations
File Operations

• There are 5 basic operations that can be performed on any files


in C programming language, either text or binary file:

• Creating a new file


• Opening an existing file
• Reading data from the existing file
• Writing more data into the file
• Closing a file
Topic 5.4: File Handling
File Handling

• In C, you can create, open, read, and write to files by declaring


a pointer of type FILE, and use the fopen() function:

FILE *fptr;
fptr = fopen(filename, mode);

• Note: A file should be opened before any operation is being


performed on it.
File Handling

• To actually open a file, use the fopen() function, which takes two
parameters:

fptr = fopen(filename, mode);

Parameter Description
filename The name of the actual file user want to open.
For example: file.txt

mode A single character that represents what the user want


to do with the file (file operations).
w – writes to a file
a – appends new data to a file
r – reads from a file
Topic 5.4.1: Create a File
Create a File

• To create a file, user can use the “w” mode inside the fopen() function.
• This mode is used to write to a file. However, if the file does not exist, it
will create one.

FILE *fptr;

fptr = fopen (“file.txt”,”w”); //creating a file

fclose(fptr); //closing a file

• Note: The file is created in the same directory as the user’s other C files,
only if nothing else is specified.
Create a File

• On computer, it looks like this.

• If you want to create a file in a specific folder, just provide the absolute
path of the file.

fptr = fopen(“C:\directoryname\file.txt”, “w”);


Topic 5.4.2: Closing File
Closing File

• The fclose() function will close the file when the work is done with it.

FILE *fptr;

fptr = fopen (“file.txt”,”w”); //creating a file

fclose(fptr); //closing a file

• This function is a good practice because it makes sure that:


- Changes are saved properly
- Other programs can use the file (if you want)
- Clean up unnecessary memory space
Topic 5.4.3: Write to a File
Write to a File
• In writing to a file we can use the “w” mode again and write something to the
file we just created.

• This mode means that the file is opened for writing. To insert content to it, you
can use the fprintf() function and add the pointer variable and some text.
fptr – sample pointer variable

FILE *fptr;
fptr = fopen (“file.txt”, “w”);
fprintf(fptr, “Sample Text”);
fclose(fptr);
Write to a File
• As a result, when we open the file on our computer, it looks like this:

FILE *fptr;
fptr = fopen (“file.txt”, ”w”);
fprintf(fptr, “Sample Text”);
fclose(fptr);
Write to a File
• Note: If you write to a file that already exists, the old content is deleted, and
the new content will be inserted:

FILE *fptr;
fptr = fopen (“file.txt”, ”w”);
fprintf(fptr, “Hello World”);
fclose(fptr);
Topic 5.4.4: Append Content to a File
Append Content to a File
• If you want to add contents to a file without deleting the old content, you can
use the “a” mode.
• This mode appends content at the end of the file;

FILE *fptr;
fptr = fopen (“file.txt”, ”a”);
fprintf(fptr, “\nSample Text”);
fclose(fptr);

• Note: Just like the “w” mode, if the file


does not exist, the “a” mode will
create a new file with the
“appended” content.
Topic 5.4.5: Read Files
Read Files

• To read from a file, users can use the “r” mode.


• This code will make the file.txt
opened for reading. FILE *fptr;
FILE *fptr;
• Next, we need to create a string fptr = fopen (“file.txt”, ”r”);
that should be big enough to store fptr = fopen (“file.txt”, ”r”);
the content of the file. char string[100];
• In order to read the content of char string[100];
file.txt, we can use the fgets(). fgets(string, 100, fptr);
• This function requires 3 parameters
Read Files

fgets(string, 100, fptr);

• The 1st parameter specifies where to store the file content, which will be in
the string array.
• The 2nd parameter specifies the maximum size of data to read, which
should match the size of string(100).
• The 3rd parameter requires a file pointer that is used to read the file (fptr).
Read Files

• To read from a file, users can use the “r” mode.


• This code will make the file.txt
opened for reading. FILE *fptr;
FILE *fptr;
FILE *fptr;
• Next, we need to create a string fptr == fopen
fopen(“file.txt”,
(“file.txt”, ”r”);
fptr “r”);
that should be big enough to store fptr = fopen (“file.txt”, ”r”);
the content of the file. char
char string[100];
string[100];
• In order to read the content of char string[100];
fgets(string,
fgets(string,100,
100,fptr);
file.txt, we can use the fgets(). fptr);
• This function requires 3 parameters printf(“%s”, string);
• Now, we can print the string, which
fclose(fptr);
will output the content of the file.
Read Files
• From previous slide: Append to a File • Output of the code: Read Files

• Note: If you remember, there were two lines of text in file.txt file. The
fgets function only reads the first line of the file.
Read Files

• To read every line of the file, you can use a while loop.

FILE *fptr;

fptr = fopen (“file.txt”, ”r”);

char string[100];

while(fgets(string, 100, fptr)){


printf(”%s”, string);
}

fclose(fptr);
Topic 5.5: Error Handling
Error Handling
• If you try to open a file for reading that does not exist, the fopen() function
will return NULL.
• As a good practice, we can use the if statement to test for NULL, and print
some text.

FILE *fptr;

fptr = fopen(“samplename.txt”, “r”);

if (fptr == NULL){
printf(“The file does not exist!”);
}

fclose(fptr);
Error Handling
• If the file exist, read the content and print it. If the file does not exist, print a
message:

FILE *fptr;

fptr = fopen(“file.txt”, “r”);


char string[100];

if (fptr != NULL){
while(fgets(string, 100, fptr)){
printf(“%s”, string);
}
} else {
printf(“The file does not exist!”);
}
fclose(fptr);
Topic 5.6: Additional Information
Additional Information

Mode Description
“r” It opens an existing file for reading only.

It opens a new file for writing. If the filename does not exist it will be created and if the file
“w”
already exists then its contents are deleted.

“a” It appends the existing file. If the filename does not exist it will be created.

It opens an existing file for reading and writing. It indicates that the file is to be read before
“r+”
writing.
It opens a new file for reading and writing. If a file with the current filename exists then it is
“w+”
destroyed and a new file name is created.
It opens an existing file for reading and appending. Its stream is positioned at the end of the
“a+”
file content.
Additional Information
• Following are the list of functions used for reading a file:

Function Syntax Description


int fscanf (FILE *stream, const char It is used for reading the formatted data from the
fscanf( )
*format,....); stream.
It stands for file get string. It is used for getting
fgets( ) char *fgets(char *str, int size, FILE *stream);
the string from a stream.
It will return the next character from the stream
fgetc( ) int fgetc (FILE *stream);
from the end of the file or an error.
int fread(void *str, size_t size, size_t num,
fread( ) It is used for reading data from a file.
FILE *stream);
Additional Information
• Following are the list of functions used for writing a file:

Function Syntax Description


int fprintf (FILE *stream, const char * It is used for writing the formatted output of the
fprintf()
format,...); stream.

fputs() int fputs(const char *str, FILE *stream); It is used for writing a line to a file.

It is opposite to fgetc() and is used for writing a


fputc() int fputc(int c, FILE *stream);
character to the stream.
int fwrite(const void *str, size_t size, size_t
fwrite() It is used for writing data to a file.
count, file *stream);
End of Discussion
Angelika S. Balagot
Instructor

You might also like