Writing on files and reading from them in C Programming - ProgrammerTech
Language:

Search

Writing on files and reading from them in C Programming

  • Share this:
Writing on files and reading from them in C Programming

Dealing with files in C

Files in C language. One of the advantages of a strong programming language is its ability to deal with files, and C language allows us to do this through the stdio.h library, where we can open files and write in them or read from them using file functions. The process of writing or reading from a file goes into three basic stages:

  1. The fopen() function is used to open the file and with this function we can determine if we want to write to a file. Or read from it, or both operations together, and it is also determined whether we want to read or write contains text txt file or binary file. binnary file such as images, video files, etc.
  2. At this stage, the file is read through the fread() function or written to it via the fwrite() function and others.
  3. The file is closed using the fclose() function.

While reading from a file or writing in it, we can move inside the file so that we can read a specific part of it or write specific content in a specific place in this file. And to do this, we precede the fread() function or the fwrite() function with another function called fseek() so that we can. With this function, we change our current location in the file by specifying the number of bytes we want to move. And if we get lost or put in the file at any time and we don't know where we are in the file after we use the fseek() function. We can go back by using ftell() which returns an on site integer number that tells us where we are. in the file according to the number of bytes we have gained from the beginning of the file.While reading from a file or writing in it, we can move inside the file so that we can read a specific part of it or write specific content in a specific place in this file. And to do this, we precede the fread() function or the fwrite() function with another function called fseek() so that we can. With this function, we change our current location in the file by specifying the number of bytes we want to move. And if we get lost or put in the file at any time and we don't know where we are in the file after we use the fseek() function. We can go back by using ftell() which returns an on site integer number that tells us where we are. in the file according to the number of bytes we have gained from the beginning of the file.

1-88.webp

In our case in the previous image, for example, if we want to move to the 25th place when the exclamation point is expressed through the command.

fseek(f, 25, SEEK_SET);

We then call the ftell() function, which will return the number 25, meaning that we are 25 bytes away from the beginning of the file. And since in ASCII the size of a character or symbol is only one byte, this means that we are 25 characters away from the beginning of the file. And do not forget also that spaces and new lines are calculated as symbols and take up space in memory like any symbol or any other letter.

 

Parameters that are used with the fopen function in C language

fopen("file path", "r")  to read
fopen("file path", "w")  To write if it was an ASCII system
fopen("file path", "wb")  To write in the case of a binary system, write the Pyth directly

We use binnary file if we want to deal with jpg, png images and audio like mp3, wave, etc. These files are used with "wb".

 

Writing to a file in C

In this paragraph we will learn how to write in a file and the next paragraph we will read from the same file in which we wrote. As we learned earlier, the file must be opened using fopen so that we can deal with it either by reading or writing, and the fopen function takes two parameters:

  1. Text representing the path of the file in the hard disk of the computer. And if the file does not exist, it will be created automatically by the fopen function.
  2. Text representing the type of operation to be performed on the file, for example the "w" symbol represents an operation. Write and "r" are read, and eventually the function returns a pointer of type FILE.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    FILE *f = fopen("/home/data/Desktop/SJO.txt", "w");
    char *s = "programmertech MOHAMMED AND SAJA";
    fwrite(s, sizeof(char), strlen(s), f);
    fclose(f);
    return 0;
}

We have created a pointer of type FILE and here we make sure that we capitalize it and the pointer is f and we type it. fopen function to open the file on the computer. And we specified its path that it is on the desktop and its name is DB, then we specified the type of operation, which is writing by typing "w". And then we define the text in this text file with a char of type pointer, which is s. We wrote the script and it is programmer tech This is the script that will be written inside the script file. Then we write the fwrite function in order to write the previous text in the file that we opened in the previous line. And the fwrite function takes the text to be written as the first parameter and we set it s because it holds the previous text.

The second parameter in this function is the size of each text written in the file, and in our case the text is an array of type char. The size of the element is the size of the char data type, i.e. 1 byte, which is the case in most cases of writing texts in files. However, there is a slight problem with this, which is that the sizes of data types in general may differ from one device architecture to another. That is why we wrote the function sizeof as a precaution, and it is exactly as if we wrote 1 in this device. Then we wrote char to be given the size of the data when we write it to this file.

And the third parameter in fwrite is a number that represents the number of elements that will be written to the file, and since each element is a char, then the number of elements is actually the number of text characters. We can either count the number of characters and write the result, or we can use the strlen function in the string.h library which is the best solution instead of counting. letter by letter, then we pass the text, which is s, and then we provide the function with the file pointer, which is f. Then we closed the file because we finished it by using the fclose function, which takes one parameter, which is the pointer to the file we opened, which is f.

When you run this program, the file will be created automatically and overwritten within it, or if the file is present, it will be overwritten. Now we will run the program and see that the output has created a file for us on the desktop as follows.

2-81.webp

As we can see that the file was created in the middle of the screen, and when we open this file we will find in it what was written while writing the code.

3-71.webp

We also noticed that the file was created on the desktop, that is, in the path we referred to, and we found the text written in it.

 

Reading from a file in C

We will rely on the previous example and read from it, first deleting. All the code we wrote in the editor previously and we start writing the reading code from a text file in C.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
    FILE *f = fopen("/home/data/Desktop/DBCS.txt", "r");
    fseek(f, 0, SEEK_END);
    unsigned int sz = ftell(f);
    fseek(f, 0, SEEK_SET);
    char *data = (char *)malloc(sz);
    fread(data, sizeof(char), sz, f);
    printf("File has been printed \n%s", data);
    free(data);
    fclose(f);
    return 0;
}

We have created a pointer of type FILE and make sure that we wrote it in capital letters and the pointer is f and we wrote the function fopen in order to open the file in the computer. And we specified its path in the desktop and its name DB, then we specified the type of operation, which is reading by typing "r". We can use the fread function to read, but in the case of reading we are missing an additional process which is knowing the size of the file we want to read from. This is because we will reserve a memory for the content we want to read. So we have to know how much memory is reserved for this file.

And to find out the size of the file, we will use the fseek and ftell functions, where we will first move through the fseek function to move to the end of the file. The ftell function will tell us its actual location in the file, i.e. the number of bytes from the beginning of the file, so we know the size of the bytes in the file. The fseek function takes three parameters. First, we pass the file we want to read from, f and the second parameter. It is an integer value to determine our location in the file and we wrote it to 0 for a reason that we will define in the third parameter.

The third operand accepts one of three cases:

The first case: SEEK_SET and this statement means that we want to go exactly to the location indicated in the second parameter, which is 0. If we keep the second parameter 0, it will move us to the beginning of the file, and if we make it 1 it will move us to the first character in the file or the first byte. Because we use the ASCII system, and this case does not serve us in the example, and we want to move to the end of the file, not the beginning.

The second case: SEEK_CUR is moving forward from our current location by the number specified in the second parameter. If we keep the second parameter 0, the fseek statement will not have any effect, but if it is 1, it will move a step forward, and this case also does not serve us here.

The third case: SEEK_END It moves to the last file, which is what we currently need in the program. Since we are at the end of the file, we will use ftell to tell us where we are in the file, and since we are at the end of the file, where we are. File size is equal to the last bytes and takes only one parameter which is the file pointer f the file path.

The ftell function returns a value and this value is of type unsigned int and we will store it. This value is in a variable named sz, for example, now the file size is stored in the sz variable. And we used the fseek function again to go back to the beginning of the file via SEEK_SET, ie we moved the beginning of the file to location 0. Then we used the fread function to read and the first parameter here will be a pointer to the place in the memory in which we intend to store the read data.

We will define a data variable of type pointer and equal to malloc and with it we reserve the capacity needed to read all the data in the file and store it in the data variable. The capacity is sz that takes the size of the file we opened and malloc returns pointer to void and we convert this pointer to the char* data type we are storing. Then we started reading the file through the fread function by using the data pointer and the second parameter representing the size of one element of the read content. The size of the data type will be char, i.e. one byte, the third parameter represents the number of elements read, which is sz, and the last fourth parameter is the file that we opened, which is f.

Finally, we print the read file that was stored in the data variable that we stored earlier by typing the text we want File has been printed and %s and then the text that was read,. Then we close the file and write free in order to unreserve the data variable that we have reserved memory for via the malloc function, and then we run the code.

4-48.webp

Tags:
Saja Alsadig

Saja Alsadig

من السودان مبرمجة مواقع ويب و تطبيقات أندرويد اتقن لغات "html, css, php, js" بالإضافة للتعامل مع اندرويد ستوديو و بناء التطبيقات, مهتمة بمجال التقنية منذ الصغر و كان لدي شقف كبير للدخول بالجامعه بقسم البرمجة و دخلته في عام 2013 و تعلمت كل شيئ ضمن الجامعة و خارجها من التعليم الذاتي و اتمنى أن أكون عند حسن ظن الجميع و إيصال الأمانة لكم, اعمل حاليا في إدارة موقع جامعة السودان.