The last article in this series dealt with characters and using loops with fgetc()
and fputc()
to read and write a series of characters or strings. Reading or writing a series of characters is such a common operation it would make sense that the C standard file I/O library has this functionality available for us.
Our demonstration program will write one line of text using fputs()
.
fputs()
is almost exactly the same as fputc()
except, as you could have guessed, it writes a string instead of a single character. The return value for fgets()
is a nonnegative number on a successful write or EOF
on error.
Example:
#include <stdio.h>
int main(void)
{
FILE *f = fopen("test", "w");
char *message = "I am a line with in a file\n";
fputs(message, f);
}
Output:
~/Desktop
➜ clang main.c
~/Desktop
➜ ./a.out
~/Desktop
➜ cat test
I am a line with in a file
~/Desktop
➜
We wrote a line of text in a file and it would make sense to read it back into the program. On the reading side of file I/O we have a string version of fgetc()
: fgets()
.
The first argument of fgets()
takes a pointer to a char array that can hold the string you're going to read in from the file. The second argument tells how many characters to read in and whatever is specified will be subtracted by 1. For example, if you want to read 100 characters, fgets()
at most will read in 99 characters. The third and last argument is a pointer to a FILE
object.
The return value of fgets()
on success is the pointer to the char array provided as the first argument. On error, a NULL pointer is returned.
Example:
#include <stdio.h>
int main(void)
{
FILE *f = fopen("test", "r");
char message[100];
if(fgets(message, 27, f) == NULL)
{
printf("Error when reading string!\n");
return 1;
}
printf("%s\n", message);
}
Output:
~/Desktop
➜ clang main.c
~/Desktop
➜ ./a.out
I am a line with in a file
~/Desktop
➜
Next
For the next entry in this series, we will talk a little more about EOF and the errors that could happen and how we can differentiate between the two.
Top comments (0)