File Handling OS LAB
File Handling OS LAB
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);
FILE is basically a data type, and we need to create a pointer variable to work with it
(fptr). For now, this line is not important. It's just something you need when working
with files.
To actually open a file, use the fopen() function, which takes two parameters:
Parameter Description
filename The name of the actual file you want to open (or create), like filena
mode A single character, which represents what you want to do with the
w - Writes to a file
a - Appends new data to a file
r - Reads from a file
Create a File
To create a file, you can use the w mode inside the fopen() function.
The w mode is used to write to a file. However, if the file does not exist, it will create
one for you:
Example
FILE *fptr;
// Create a file
fptr = fopen("filename.txt", "w");
Note: The file is created in the same directory as your other C files, if nothing else is
specified.
Read a File
In the previous chapter, we wrote to a file using w and a modes inside
the fopen() function.
Example
FILE *fptr;
Next, we need to create a string that should be big enough to store the content of the
file.
For example, let's create a string that can store up to 100 characters:
Example
FILE *fptr;
In order to read the content of filename.txt, we can use the fgets() function.
Example
1. The first parameter specifies where to store the file content, which will be in
the myString array we just created.
2. The second parameter specifies the maximum size of data to read, which should
match the size of myString (100).
3. The third parameter requires a file pointer that is used to read the file (fptr in
our example).
Now, we can print the string, which will output the content of the file:
Example
FILE *fptr;
Write To a File
Let's use the w mode from the previous chapter again, and write something to the file
we just created.
The w 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 (fptr in our example) and some
text:
Example
FILE *fptr;
As a result, when we open the file on our computer, it looks like this:
Note: If you write to a file that already exists, the old content is deleted, and the new
content is inserted. This is important to know, as you might accidentally erase existing
content.
For example:
Example
Example
FILE *fptr;
As a result, when we open the file on our computer, it looks like this: