The goal of our program is to open a file, count characters in it and display the result. Let's start by including necessary libraries:
#include <stdio.h>
#include <string.h>
The stdio.h file will be
as always necessary for us to print
messages on the terminal, but it will also
let us operate on files. The string.h
file will give us necessary functions for making
more complex operations on arrays of characters.
After including our libraries, we can begin with the main function.
int main(){
return 0;
}
For now the program does nothing important,
it will immidiately exit on starting it.
Our program needs to open our file first.
To do that, we will use some functions the
included file stdio.h gives us.
We need to create a new variable that will
be a pointer for our file, it will store the
address of opened file in our program.
FILE *fileptr;
The variable is made out of a special
FILE type. However, the file is
not opened yet. We will use a fopen()
function from the same stdio.h
header file. We will need to put the results
of that function that returns them into
our variable that is a pointer for our file.
Our program has loaded the file into the memory
but we know only the address of the file
in the memory. That's enough for us to
operate on our file.
fileptr = fopen("hello.txt", "r");
We gave the fopen() function
some arguments. The first argument is file name
the program is going to open. In our case the
program will open a file named test.txt.
The second argument is mode in which the
program will open the file. In our case
r means that our program can only
read the contents of the file, but can't edit it.
If we would want our program to be able to
edit the file, the mode would be set to
w, which lets the program to both
read and write to the file. However, so far, we don't
need our program to write to the file it will open,
since we only count length of opened file.
Our program may fail on opening the file,
for example when the file with given name simply
doesn't exist. By default only the fopen()
function will fail silently and the program will go further.
To avoid bugs, we will want our program to check if function
responsible for opening the file fails or not.
To ease our life, the fopen() function
returns NULL when it fails, which means
that it put the NULL into our file pointer
variable, and to make our program check if opening the file failed,
we can check if our file pointer contains the NULL
variable that the fopen() returned us.
if(fileptr == NULL){
fprintf(stderr, "Could not open file.\n");
return 1;
}
fprintf() is a special function to
print messages of given standard type. In our case we have put
stderr, which lets the system know that we print
an error message. After that, we return our main function
with value 1 (0 means success,
any other number than that often means failure. Not always),
which makes our program exit while throwing returned value to
the system. It's an exit code. To later check which exit code
the program returned, we can do echo $? in bash shell.
We are done opening the file and checking if everything went all right. We can begin operating on our opened file.
Since we want our program to count, we will need a variable that will count. We count characters, and since so far our prorgam knows only the address in memory of our opened file, we will need another variable that will actually store the contents of the file. Then when we will count the characters, we will count them from that variable that got file contents. Let's initialize our two variables.
int chars = 0;
char filestring[256] = { 0 };
At the start of the program, our characters counter chars
will be 0 since we haven't counted any characters yet.
The counter variable is an integer. The second variable
filestring is an array of characters. It will store contents
of opened file by reading it, but now it's empty. We will
call it a buffer. We have initialized
256 elements, which should be enough for now.
In order to count characters in a file, our program needs to
put the file contents into our filestring array, then from
that array the program can count characters. We will use another
special function called fgets(), that is responsible
for copying file contents by knowing our file pointer. It's enough
for the function to know only the address of the opened file,
then it will get the contents itself. The function will copy the
collected contents to the filestring buffer we will also give
in function parameters.
fgets(filestring, sizeof(filestring), fileptr)
We have three function parameters in total. The first one is destination
to where the function has to copy the contents. The second argument is
how much it has to copy to given buffer. In our case we use neat function
called sizeof() that returns size of given variable.
The last and third argument is from where we get the contents.
In our case it's our file pointer variable, fileptr.
Our filestring buffer now contains file contents,
which means that we can count the characters from this buffer.
To do that, we will use strlen() function (from
string.h header file this time) that returns
a number that is length of given string. Then we add that returned
number to our chars variable.
chars += strlen(filestring);
That's it! Our program has counted how much characters we have in a file.
Now since we have such number stored in chars, we
can display it on the terminal.
printf("Characters: %d\n", chars);
This statement tells to display the Characters: x message,
where x is the number of characters. In printf()'s
case, we tell that %d is the place where to display an integer number,
and that integer number is chars we put in second argument.
Before our program exits, it has to do very important thing: close
the file. If we forget about this, even after the program exits, the system
will still see that the file is opened, and if other programs would ever want
to access that file, the system would say to them that This file is occupied!,
even after the program that opened the file already ended. To close the file,
we will use an fclose() function.
fclose(fileptr);
In the first and only argument we give file pointer variable, which makes the function know which file to close. After that important thing, we can finally make the program exit with exit code 0, telling the system that the program ended successfully, without problems.
return 0;
Done. Let's take a look at whole code. Nothing stops you from copy-pasting all of it right now, but better if you carefully read the article and write the code by yourself. :)
#include <stdio.h>
#include <string.h>
int main(){
FILE *fileptr;
fileptr = fopen("hello.txt", "r");
if(fileptr == NULL){
fprintf(stderr, "Could not open file.\n");
return 1;
}
int chars = 0;
char filestring[256] = { 0 };
fgets(filestring, sizeof(filestring), fileptr);
chars += strlen(filestring);
printf("Characters: %d\n", chars);
fclose(fileptr);
return 0;
}
To make sure everything is alright, let's compile our code to an executable file then run it.
gcc fcount.c -o fcount
./fcount
The program will say: Could not open file, if we forgot to
create hello.txt file. We will create this text file
and put a Hello, World! into it, then save it. Make sure
that the text file is located next to our executable file. Now when we run our program, it should
display this:
Characters: 14
Notice that it said that we have 14 characters
but Hello, World! is 13. This is because
most text editors add an extra special character
that is encoded as End of File
(EOF). That can be clearly seen
from a hex dump of our hello.txt
file.
00000000: 4865 6c6c Hell
00000004: 6f2c 2057 o, W
00000008: 6f72 6c64 orld
0000000c: 210a !.
All material under this website is licensed under CC BY-SA 4.0